使用GROUP BY语句对行进行求和

时间:2012-01-16 19:58:08

标签: mysql sql

我在不同的市场有多个产品销售,我需要总结每个产品的总数。开始:

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 个答案:

答案 0 :(得分: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允许您仅在title子句中包含GROUP BY,其中大多数其他RDBMS也会要求您列出GROUP BY中的其他非聚合列。具体来说,就是partner_share_currency

答案 1 :(得分: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