Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/actionscript-3/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL案例语句透视问题_Mysql - Fatal编程技术网

MySQL案例语句透视问题

MySQL案例语句透视问题,mysql,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_

请建议将表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
试试这个

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

查询中的问题:

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
的字段

解决方案:

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()
分组依据

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的另一种选择:

您尝试了什么吗?是的,我为每个类型添加了大小写,但它给出了3行,但我在1中查找row@jacob53:您的表中将有多少类型?选择用户\u id,当type=1时,选择case,然后在末尾创建为Type1,当type=2时,案例在末尾创建为Type2,当type=3时,案例在末尾从t1创建为Type3