2013-07-16 123 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