2012-12-05 54 views
2

我對PHP/MySQL沒有太多經驗。我有一個有3個字段的表格:id,particularamount,如下所示。顯示結果行組和總和各組值

id particular amount 
1 Fees   5000 
2 Fees   3000 
3 Bill   9000 
4 Fees   4000 
5 Bill   3000 
6 Expense  2000 
7 Fees   1000 

我要顯示在組中的數據以及每個單獨組的總和,就像這樣:

particular amount 
Fees   5000 
Fees   3000 
Fees   4000 
Fees   1000 
**Total  13000** 
Bill   9000 
Bill   3000 
**Total  12000** 
Expense  2000 
**Total  2000** 

我嘗試此查詢SELECT SUM(amount), particular FROM sale_expense GROUP BY particular,並添加了所有的值,但它是該組中沒有顯示,因爲我需要顯示數據

+0

你看了'GROUP BYMySQL文檔中的「0 WITH ROLLUP」選項? – Barmar

回答

1

嘗試這個SQL:

 
SELECT particular, SUM(amount) AS total FROM tablename GROUP BY particular 

這應該會給你每組的總數。
UPDATE: 試試這個

$sql = "SELECT particular, SUM(amount) AS total FROM tablename GROUP BY particular"; 
$result = mysql_query($sql); 
while($row = mysql_fetch_array($result)){ 
    $sql2 = "SELECT * FROM tablename WHERE particular = '".$row['particular']."'"; 
    $result2 = mysql_query($sql2); 
    while($row2 = mysql_fetch_array($result2)){ 
     echo $row2['particular']. " ".$row['amount']; 
     echo "\n"; 
    } 
    echo "Totol: ".$row['total'].""; 
}

+0

是的,我可以添加所有的值,但我也想顯示組。 – user1879786

+0

不要在註釋中放置代碼。 – Barmar

+0

請參閱上面的更新。 –

0

可以聯合查詢一起:

select particular, amount 
from ((select id, particular, amount 
     from sales_expense se 
    ) union all 
     (select 99999 as id, concat('Total: ', particular), sum(amount) as amount 
     from sales_expense se 
     group by particular 
    ) 
    ) t 
group by particular 
order by id 
+0

我嘗試你的查詢,但它不工作,因爲我想顯示數據。 – user1879786

+0

我不明白。查詢應該返回你想要的數據。 –

0

試試這個:

(SELECT 
    particular, 
    amount 
    FROM sale_expense) 
UNION 
(SELECT 
    CONCAT(particular," - total") AS particular, 
    SUM(amount) AS amount 
    FROM sale_expense 
    GROUP BY particular) 
ORDER BY particular ASC 
+0

它不起作用。 – user1879786

+0

我更正爲第二個查詢「AS特別」。我認爲這應該工作。 –

+0

您的SQL語法有錯誤;檢查與您的MySQL服務器版本相對應的手冊,以便在''UNION(SELECT CONCAT(特別是''total'')附近使用正確的語法)特別是,SUM(金額)AS amou'在第1行 – user1879786

2
SELECT particular, id, sum(amount) amount 
FROM TableName 
GROUP BY particular, id WITH ROLLUP 

fiddle

+0

這是您的查詢結果關鍵量 平衡 \t 平衡 \t 平衡 \t 租金 \t 租金 \t 工資 \t 工資 \t 薪金 \t 話費 \t 話費 \t 話費 – user1879786

+0

什麼是你的問題?具有空id的行是這些組的小計。 – Barmar