MySQL CASE Statement Pivot问题

时间:2015-02-19 12:17:05

标签: mysql

请建议将表格1转换为表格2 ..

Actual Result:  
      User_id type   created_at
        1        1     2015-02-01
        1        2     2015-03-10
        1        3     2015-04-22 



Expected Result:

    user_id, type1_date, type2_date, type3_date

查询:

select user_id, 
       case when type=1 then created_at end as Type1,
       case when type=2 then created_at end as Type2,
       case when type=3 then created_at end as Type3 
from t1

2 个答案:

答案 0 :(得分:1)

查询中的问题:

select user_id, 
       case when type=1 then created_at end as Type1,
       case when type=2 then created_at end as Type2,
       case when type=3 then created_at end as Type3 
from t1

您尚未使用聚合函数MAX()。因此,查询不会消除NULL值的字段。

<强>解决方案:

使用MAX()GROUP BY

SELECT user_id,
       MAX(CASE WHEN type=1 THEN created_at END) AS type1_date,
       MAX(CASE WHEN type=2 THEN created_at END) AS type2_date,
       MAX(CASE WHEN type=3 THEN created_at END) AS type3_date
FROM t1
GROUP BY user_id

如果类型列值有限,则这是pivot的替代方法:

答案 1 :(得分:0)

试试这个。

SELECT User_id,
     MAX(CASE WHEN type = 1 THEN created_at END) AS type1_date,
     MAX(CASE WHEN type = 2 THEN created_at END) AS type2_date,
     MAX(CASE WHEN type = 3 THEN created_at END) AS type3_date
FROM {your_table}
GROUP BY User_id