按日期+其他字段对多个字段进行求和

时间:2013-02-16 04:04:50

标签: mysql select group-by

我有一个包含3列的表,如下所示。我想总结每个TYPE的成本(仅为0/1/2),然后按月和年(DATE字段)对其进行分组,所有这些都使用select语句。

+------------+------+-------+
| DATE       | TYPE | COST  |
+------------+------+-------+
| Feb-1-2003 |  0   | 19.40 |
| Feb-5-2010 |  1   | 28.10 |
| Mar-3-2011 |  2   | 64.20 |
| Sep-8-2012 |  0   | 22.60 |
| Dec-6-2013 |  1   | 13.50 |
+------------+------+-------+

输出如下:

+----------+------------+------------+------------+
| PERIOD   | TYPE0      | TYPE1      | TYPE2      |
+----------+------------+------------+------------+
| Jan 2003 | 123123.12  | 23432.12   | 9873245.12 |
| Feb 2003 | 123123.12  | 23432.12   | 9873245.12 |
| Mar 2003 | 123123.12  | 23432.12   | 9873245.12 |
etc...
+----------+------------+------------+------------+

有人可以帮助解决这个选择声明吗?

1 个答案:

答案 0 :(得分:3)

Mysql不是为透视查询而设计的。最好用其他语言进行聚合。但这并不是说这是不可能的:

SELECT
    CONCAT(MONTH(DATE), ' ', YEAR(DATE)) AS PERIOD,
    SUM(IF(TYPE = 0, COST, 0)) AS TYPE0,
    SUM(IF(TYPE = 1, COST, 0)) AS TYPE1,
    SUM(IF(TYPE = 2, COST, 0)) AS TYPE2
FROM
    t1
GROUP BY
    PERIOD