0

我有一个包含 3 列的表格,如下所示。我想总结每种类型的成本(仅 0/1/2),然后按月份和年份(日期字段)对其进行分组,所有这些都使用 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...
+----------+------------+------------+------------+

有人可以帮助这个选择语句吗?

4

1 回答 1

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
于 2013-02-16T04:08:37.710 回答