不使用COALESCE将多行分组为一行

时间:2013-10-04 12:24:07

标签: sql

如果我有一张如下表格:

Date    Name    Number    Period1    Period2    Period3  
-------------------------------------------------------
23-Oct  Barry   453       NULL       NULL       Room 4
23-Oct  Barry   453       NULL       Room 8     NULL
24-Oct  Barry   453       Room 2     NULL       NULL
23-Oct  Mary    139       Room 3     NULL       Room 4
23-Oct  Mary    139       NULL       Room 6     NULL
24-Oct  Mary    139       NULL       NULL       Room 9
24-Oct  Mary    139       Room 1     NULL       NULL

我如何才能最好地查询它以获得下面的输出,即按日期,人物和期间分组?

Date    Name    Number    Period1    Period2    Period3  
-------------------------------------------------------
23-Oct  Barry   453       NULL       Room 8     Room 4
23-Oct  Mary    139       Room 3     Room 6     NULL
24-Oct  Barry   453       Room 2     NULL       NULL
24-Oct  Mary    139       Room 1     NULL       Room 9

1 个答案:

答案 0 :(得分:1)

SELECT Date,
       Name,
       Number,
       MAX(Period1) AS Period1,
       MAX(Period2) AS Period2,
       MAX(Period3) AS Period3
FROM   T
GROUP  BY Date,
          Name,
          Number