2012-01-16 157 views
0

我在不同市場有多個產品銷售,我需要總結每個標題的總計。要啓動:使用GROUP BY語句合計行

mysql> SELECT title, partner_share_currency, us_earnings_usd, cad_earnings_cad 
     FROM raw_financials WHERE title LIKE "%Gamers%"; 
+--------+------------------------+-----------------+------------------+ 
| title | partner_share_currency | us_earnings_usd | cad_earnings_cad | 
+--------+------------------------+-----------------+------------------+ 
| Gamers | USD     |   3.2500 |   0.0000 | 
| Gamers | CAD     |   0.0000 |   4.0000 | 
| Gamers | USD     |   4.5000 |   0.0000 | 
+--------+------------------------+-----------------+------------------+ 

這是我目前正在做得到GROUP BY標題:

mysql> SELECT title, us_earnings_usd, cad_earnings_cad 
     FROM raw_financials WHERE title LIKE "%Gamers%" GROUP BY title; 
+--------+-----------------+------------------+ 
| title | us_earnings_usd | cad_earnings_cad | 
+--------+-----------------+------------------+ 
| Gamers |   3.2500 |   0.0000 | 
+--------+-----------------+------------------+ 

正如你所看到的,它不求和值的行。我將如何改變SELECT語句,它總結了值的行,給我:

+--------+-----------------+------------------+ 
| title | us_earnings_usd | cad_earnings_cad | 
+--------+-----------------+------------------+ 
| Gamers |   7.7500 |   4.0000 | 
+--------+-----------------+------------------+ 
+2

'group by'子句不做求和。他們只是說哪些行應該被「摺疊」以用於聚合函數。你仍然必須告訴'sum()'函數(或其他聚合函數)應該應用於哪些字段。 – 2012-01-16 20:01:01

回答

2

試着這麼做:

mysql> SELECT title, SUM(us_earnings_usd) AS us_earnings_usd, SUM(cad_earnings_cad) AS cad_earnings_cad 
     FROM raw_financials WHERE title LIKE "%Gamers%" GROUP BY title; 

SUM是將各組操作的功能,當你在你的發言中有這個GROUP BY條款。有關更多類似功能,請參閱MySQL aggregate functions

+1

如何按標題分組並選擇非列函數('partner_share_currency')? – gdoron 2012-01-16 20:01:14

+0

這是直接複製出來的問題,我只是在總和函數中添加的。 OP也可能需要通過'partner_share_currency'進行分組,以獲得結果,如示例中所示。 – 2012-01-16 20:04:12

+1

感謝您指出,這是一個錯誤 - 我會改變這個問題來反思。 – David542 2012-01-16 20:05:30

3

您需要總計SUM()來總計行數。你只有一個GROUP BY

SELECT 
    title, 
    partner_share_currency, 
    SUM(us_earnings_usd) AS usd, 
    SUM(cad_earnings_cad) AS cad 
FROM raw_financials 
WHERE title LIKE '%Gamers%' 
GROUP BY title, partner_share_currency 

注意,MySQL將允許你只titleGROUP BY子句,其中大多數其他RDBMS還需要你以列出GROUP BY其他非集合列中包含。具體來說,這就是partner_share_currency