按月和货币分组MySQL

时间:2014-03-21 13:22:20

标签: php mysql

我有一张表格,其中包含我在网上商店的所有销售情况。 它看起来像这样:

saletime            | saleprice  | fee  | currency
2014-01-01 00:51:27 | 89.00      | 6.9  | USD
2014-01-01 01:20:27 | 249.00     | 9.9  | SEK
2014-01-01 02:31:27 | 849.00     | 19.9 | SEK

我需要获得按月份和货币分组的总数。

结果应如下所示:

Month   | Sum(saleprice) | Sum(fee) | Currency
01-2014 | 9829827.00     | 38738.00 | USD
01-2014 | 443827.00      | 738.00   | SEK
01-2014 | 439827.00      | 4738.00  | NOK

02-2014 | 9829827.00     | 38738.00 | USD
02-2014 | 443827.00      | 738.00   | SEK
02-2014 | 439827.00      | 4738.00  | NOK

03-2014 | 9829827.00     | 38738.00 | USD
03-2014 | 443827.00      | 738.00   | SEK
03-2014 | 439827.00      | 4738.00  | NOK

如果没有太多关于高级分组的知识,我就尝试了一些

的方法
SELECT SUM(saleprice), SUM(fee), currency 
FROM sales
GROUP BY (month(saletime), year(saletime)), currency

但我失败了。怎么解决这个问题?

2 个答案:

答案 0 :(得分:3)

您需要按月+年分组,然后按货币分组:

SELECT DATE_FORMAT(saletime,"%m-%Y") AS `Month`, SUM(saleprice), SUM(fee), currency
FROM sales
GROUP BY DATE_FORMAT(saletime,"%m-%Y"), currency

如果您想将所有美元货币分组到一个组中,其余货币分组到另一个组中:

SELECT DATE_FORMAT(saletime,"%m-%Y") AS `Month`, SUM(saleprice), SUM(fee),
  IF(currency = 'USD', 'USD', 'Other') AS currency
FROM sales
GROUP BY DATE_FORMAT(saletime,"%m-%Y"), currency = 'USD'

答案 1 :(得分:1)

你几乎做到了,试试:

SELECT sum(saleprice), sum(fee), currency 
FROM sales
GROUP BY DATE_FORMAT( creation_date, '%Y-%m'), currency