我有一個表(「轉儲」)的交易,我想列出的總額,按類別分組,每月,如:本月|類別|類別ID |和。涉及的表是這樣的:獲取對不同行的SUM()在MySQL
TABLE dump: id INT date DATE event VARCHAR(100) amount DECIMAL(10, 2)
TABLE dump_cat: id INT did INT (id in dump) cid INT (id in categories)
TABLE categories: id INT name VARCHAR(100)
現在,我嘗試使用該查詢:
SELECT SUBSTR(d.date,1,7) AS month, c.name, c.id AS catid, SUM(d.amount) AS sum FROM dump as d, dump_cat as dc, categories AS c WHERE dc.did = d.id AND c.id = dc.cid AND SUBSTR(d.date, 1, 7) >= '2008-08' GROUP BY month, c.name ORDER BY month;
但對於大多數類別的總和的兩倍大,因爲它應該。我的猜測是,這是因爲連接返回多行,但在字段部分中添加「DISTINCT d.id」沒有任何區別。的查詢返回的內容的示例是:
+---------+--------------------------+-------+-----------+ | month | name | catid | sum | +---------+--------------------------+-------+-----------+ | 2008-08 | Cash | 21 | -6200.00 | | 2008-08 | Gas | 8 | -2936.19 | | 2008-08 | Rent | 1 | -15682.00 |
其中作爲
SELECT DISTINCT d.id, d.amount FROM dump AS d, dump_cat AS dc WHERE d.id = dc.did AND SUBSTR(d.date, 1, 7) ='2008-08' AND dc.cid = 21;
返回
+------+----------+ | id | amount | +------+----------+ | 3961 | -600.00 | | 2976 | -200.00 | | 2967 | -400.00 | | 2964 | -200.00 | | 2957 | -300.00 | | 2962 | -1400.00 | +------+----------+
這樣總計3100,一半以上列出的總和。如果我從最後一個查詢中刪除「DISTINCT d.id」,則每行都列出兩次。我認爲這是問題,但我需要幫助來弄清楚如何解決它。提前致謝。
補充:如果我收集轉儲和dump_cat表爲一體,具有
CREATE table dumpwithcat SELECT DISTINCT d.id, d.date, d.event, d.amount, dc.cid FROM dump AS d, dump_cat AS c WHERE c.did = d.id;
,並做了查詢該表,一切工作正常使用正確的總和。有沒有辦法在原始查詢中做到這一點,與子查詢或類似的東西?
如果您取出SUM和GROUP BY並選擇金額,您是否看到重複的記錄? – 2009-08-27 19:20:37
Eric:是的。我如何擺脫它們? :) – Par 2009-08-27 19:52:29
如果你加入dump和dump_cat你會得到任何重複嗎?如何dump_cat和類別? – 2009-08-27 20:26:30