根据条件将查询数据合并为一行

时间:2018-05-23 14:01:35

标签: mysql case

我有以下方式的数据

code1  code2  new_status  created_at   old_status
A       1        S2        x            S1
A       1        S3        y            s2
A       1        S4        z            S3
B       2        S3        P            S1

查询后我想以下列方式获取数据

code1   code2   S1   S1_date  S2   S2_date   s3   s3_date   s4    s4_date
A        1       0      0      1    x         1     y        1        z
B        2       0      0      0    0         1     P        0        0

我目前正在使用案例来区分状态,但为每个状态获取不同的行。我希望它如上所示组合在一起。

1 个答案:

答案 0 :(得分:0)

在MySQL中实现这个并不是一个好主意,因为根据我的知识,MySQL并不支持PIVOT。

但是,您仍然可以使用以下SQL在MySQL中获得所需的结果。

SQL:

select code1,code2,
       max(case when new_status='S1' then 1 else 0 end) S1,
       max(case when new_status='S1' then created_dt else 0 end) S1_date,
       max(case when new_status='S2' then 1 else 0 end) S2,
       max(case when new_status='S2' then created_dt else 0 end) S2_date,
       max(case when new_status='S3' then 1 else 0 end) S3,
       max(case when new_status='S3' then created_dt else 0 end) S3_date,
       max(case when new_status='S4' then 1 else 0 end) S4,
       max(case when new_status='S4' then created_dt else 0 end) S4_date
from xyz
group by code1,code2;

从示例数据到输出的示例:

mysql> create table xyz(code1 varchar(20),code2 varchar(20),new_status varchar(20),created_dt varchar(20),old_status varchar(20));
Query OK, 0 rows affected (0.46 sec)

mysql> insert into xyz values
    -> ('A','1','S2','x','S1'),
    -> ('A','1','S3','y','s2'),
    -> ('A','1','S4','z','S3'),
    -> ('B','2','S3','P','S1');
Query OK, 4 rows affected (0.05 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> 
mysql> select code1,code2,
    ->        max(case when new_status='S1' then 1 else 0 end) S1,
    ->        max(case when new_status='S1' then created_dt else 0 end) S1_date,
    ->        max(case when new_status='S2' then 1 else 0 end) S2,
    ->        max(case when new_status='S2' then created_dt else 0 end) S2_date,
    ->        max(case when new_status='S3' then 1 else 0 end) S3,
    ->        max(case when new_status='S3' then created_dt else 0 end) S3_date,
    ->        max(case when new_status='S4' then 1 else 0 end) S4,
    ->        max(case when new_status='S4' then created_dt else 0 end) S4_date
    -> from xyz
    -> group by code1,code2;
+-------+-------+------+---------+------+---------+------+---------+------+---------+
| code1 | code2 | S1   | S1_date | S2   | S2_date | S3   | S3_date | S4   | S4_date |
+-------+-------+------+---------+------+---------+------+---------+------+---------+
| A     | 1     |    0 | 0       |    1 | x       |    1 | y       |    1 | z       |
| B     | 2     |    0 | 0       |    0 | 0       |    1 | P       |    0 | 0       |
+-------+-------+------+---------+------+---------+------+---------+------+---------+
2 rows in set (0.00 sec)