MySQL:将多行(空值)组合成一行?

时间:2015-03-09 03:35:28

标签: mysql sql

我有一个名为code_status的表:

  Code     Message
    1     "Start"
    2     "In process"
    3     "Finish"

另一张名为历史的表

 ID   Code    Name      time_date
 1     2      Jon       1/2/15
 31    1      Abby      2/1/15
 12    3      Sara      3/3/15
 31    2      Abby      2/3/15
 31    3      Abby      2/5/15
 8     2      Max       1/22/15

我想使用以下架构创建history_view:

history_view (id, name, start_date, process_date, finish_date)

如果没有给出日期,它只会是NULL

所以它看起来像

ID   Name    start_date    process_date      finish_date
31   Abby     2/1/15          2/3/15           2/5/15
1    Jon      NULL            1/2/15            NULL
... etc

所以我开始做:

CREATE VIEW history_view
AS SELECT h.id, h.name, 
(CASE WHEN h.code = 1 THEN time_date) AS start_date,
(CASE when h.code = 2 THEN time_date) AS process_date,
(CASE when h.code = 3 THEN time_date) AS finish_date
FROM history h;

我会得到如下结果:

ID   Name    start_date    process_date      finish_date
31   Abby     2/1/15         NULL               NULL
31   Abby      NULL          2/3/15             NULL
31   Abby      NULL          NULL             2/5/15
... ETC

有没有办法将行合并在一起?

1 个答案:

答案 0 :(得分:2)

当您说consolidate时,您指的是aggregation,您可以使用汇总功能,例如min

CREATE VIEW history_view
AS SELECT h.id, h.name, 
min(CASE WHEN h.code = 1 THEN time_date) AS start_date,
min(CASE when h.code = 2 THEN time_date) AS process_date,
min(CASE when h.code = 3 THEN time_date) AS finish_date
FROM history h
group by h.id, h.name;