2013-05-21 85 views
1

我需要幫助編寫一個mysql查詢SUM列中的金額,其中列值可能會有所不同,具體取決於它包含的值。這是我的表格的一個例子。Mysql查詢總和動態金額

account  type   amount 
-------  ----   ------ 
Dell  Inventory 500.00 
Microsoft Inventory 100.00 
Cisco  Inventory 300.00 
Dell  Inventory 400.00 
Webhosting Service  15.00 

這是我到目前爲止,它沒有太多,但我想不出一個好辦法做到這一點。

$result = mysql_query("SELECT * FROM table WHERE type = 'Inventory'"); 
while($row = mysql_fetch_array($result)){ 
    Sum the amounts for each account type. The account types are not fixed, will change regularly 
} 

正如上面我的通知上說,該帳戶的字段不會那麼固定的,我不能硬編碼我的查詢與該帳戶的名稱。

然後我想要一份報告詳細說明每個帳戶的總計。

Dell $900 
Microsoft $100 
Cisco $300 

感謝您的幫助!

+0

我不在預期的結果中看不到任何類型...... –

回答

4

您需要使用匯總函數SUM()來獲取每個帳戶的總金額。

SELECT account, SUM(amount) totalAmount 
FROM tableName 
WHERE type = 'inventory' 
GROUP BY account 
+0

謝謝,我如何通過mysql_fetch_array獲取值?我是否必須遍歷它? – Tom

+0

是的,因爲可以有多個'account'。 http://php.net/manual/en/function.mysql-fetch-array.php –

+0

謝謝,作品! – Tom

1

我想你可以通過account使用GROUP BY,以便將記錄,以便您可以使用SUM()函數來彙總所有金額

SELECT account, SUM(amount) as total 
FROM table 
WHERE type = 'inventory' 
GROUP BY account 
1
SELECT `account`,sum(`amount`) FROM `table_name` WHERE `type`='Inventory' group by `account`