2013-07-16 81 views
0

我使用Google Charts绘制饼图。为了绘制它,两列数据格式是必要的。这里没有给出绘制谷歌图表的代码,因为它是未来实施的一部分。对于从数据库中获取数据,我写了下面的代码:如何将查询结果从多列转换为两列?

<?php 
    $con=mysql_connect("localhost","XYZ","pqrs") or die("Failed to connect with database!!!!"); 
    mysql_select_db("LMN", $con); 

    $sql =" SELECT COUNT(*) 'carried_out', SUM(transaction_status = 'success') success, "; 
    $sql .=" SUM(transaction_status = 'inprocess') inprocess, SUM(transaction_status = 'fail') fail, "; 
    $sql .=" SUM(transaction_status = 'cancelled') cancelled FROM user_transaction GROUP BY transaction_status"; 

    $sth = mysql_query($sql) or die(mysql_error()); 

    /*$result = mysql_fetch_array($sth, MYSQL_ASSOC); 
    print_r($result); die;*/ 
    $rows = array(); 
    //flag is not needed 
    $flag = true; 
    $table = array(); 
    $table['cols'] = array(

    // Labels for your chart, these represent the column titles 
    // Note that one column is in "string" format and another one is in "number" format as pie chart only required "numbers" for calculating percentage and string will be used for column title 
    array('label' => 'Transaction Category', 'type' => 'string'), 
    array('label' => 'Percentage', 'type' => 'number') 

); 
//print_r($table); 

$rows = array(); 
while($r = mysql_fetch_assoc($sth)) { 
    $temp = array(); 
    // the following line will be used to slice the Pie chart 
    $temp[] = array('v' => (string) $r['user_transaction']); 
//print_r($temp); 
    // Values of each slice 
    $temp[] = array('v' => (int) $r['transaction_count']); 
    //print_r($temp); 

    $rows[] = array('c' => $temp); 
    //print_r($rows); 

} 

$table['rows'] = $rows; 

//print_r($table); 

$jsonTable = json_encode($table); 
//echo $jsonTable; 


    ?> 

如果我执行上面的查询,我得到以下结果:

carried_out  success  inprocess fail cancelled 
18 18 0 0 0 
8 0 8 0 0 
64 0 0 0 64 

但我想要的结果到名为transactions_category两列和transaction_count。你能帮我做什么改变,我应该做的SQL查询,以实现这一目标?提前致谢。

回答

1

尝试此查询

SELECT 'Success' as transactionType, count(*) from user_transaction where transaction_status = 'success'; 
UNION 
SELECT 'In Process' as transactionType, count(*) from user_transaction where transaction_status = 'inprocess' 
UNION 
SELECT 'Fail' as transactionType, count(*) from user_transaction where transaction_status = 'fail' 
UNION 
SELECT 'Cancelled' as transactionType, count(*) from user_transaction where transaction_status = 'Cancelled'; 

采用联合运营商从多个查询结果集组合成一个结果集。

+0

我试过你的查询,但它给出了错误。你能给我一个查询的确切可运行代码吗?还有一件事我注意到,你没有在查询中的任何地方提到FROM表名。 – PHPLover

+0

使用from子句更新的代码...现在它已经丢失了,但是我没有你的表来对它进行测试。 – Orangepill