MySQL 5.6将行移动到列中(pivot函数)

时间:2016-07-13 06:52:17

标签: mysql pivot

我们有以下输入:

ID,MONTH,AMOUNT
1,1,1.1
1,2,2.1
1,3,3.1

我们希望将其输出为:

ID,AMOUNT_JAN,AMOUNT_FEB,AMOUNT_MAR
1,1.1,2.1,3.1

到目前为止我们得到的查询:

SELECT ID,
CASE WHEN MONTH = '1' THEN AMOUNT END AS AMOUNT_JAN,
CASE WHEN MONTH = '2' THEN AMOUNT END AS AMOUNT_FEB,
CASE WHEN MONTH = '3' THEN AMOUNT END AS AMOUNT_MAR
FROM TEST2

只能生成如下输出:

ID,AMOUNT_JAN,AMOUNT_FEB,AMOUNT_MAR
1,1.1,NULL,NULL
1,NULL,2.1,NULL
1,NULL,NULL,3.1

任何一位大师能开导吗?

为方便起见,可以使用SQL Fiddle:

http://sqlfiddle.com/#!9/017d9c/3

3 个答案:

答案 0 :(得分:1)

添加enumGROUP BY功能:

MAX

SQLFiddle Demo

答案 1 :(得分:1)

您必须在GROUP BY子句中添加SELECT并使用条件聚合

SELECT ID,
       MAX(CASE WHEN MONTH = '1' THEN AMOUNT END) AS AMOUNT_JAN,
       MAX(CASE WHEN MONTH = '2' THEN AMOUNT END) AS AMOUNT_FEB,
       MAX(CASE WHEN MONTH = '3' THEN AMOUNT END) AS AMOUNT_MAR
FROM TEST2
GROUP BY ID

Demo here

答案 2 :(得分:0)

从技术上讲,你可以尝试:

SELECT
  ID
  , (SELECT AMOUNT FROM TEST2 WHERE ID = T_outer.ID AND MONTH = 1) AS AMOUNT_JAN
  , (SELECT AMOUNT FROM TEST2 WHERE ID = T_outer.ID AND MONTH = 2) AS AMOUNT_FEB
  , (SELECT AMOUNT FROM TEST2 WHERE ID = T_outer.ID AND MONTH = 3) AS AMOUNT_MAR
FROM TEST2 T_outer
GROUP BY ID
;

查看实际操作:SQL Fiddle

请评论是否需要调整/进一步详细说明。