SQL根据ID组合行?

时间:2018-01-29 21:15:23

标签: sql sql-server

我有一个表,它需要组合多行数据。

Name    ColumnName  ID  Value
T1        Time      1   2:00 PM
T1        Time      2   3:00 PM
T1        Date      1   1/29/18
T1        Date      2   1/30/18
T1        Text      1   Apple
T1        Text      2   Orange
T1        Start     1   10:00 AM
T1        Start     2   8:00 AM

根据这些数据,我希望获得这样的行,每行都基于ID:

Name  Time    Date     Text    Start
T1    2:00PM  1/29/18  Apple   10:00AM
T1    3:00PM  1/30/18  Orange  8:00AM

这会是需要转动的吗?

1 个答案:

答案 0 :(得分:4)

您可以使用条件聚合:

select name,
       max(case when columnname = 'time' then value end) as time,
       max(case when columnname = 'Date' then value end) as Date,
       max(case when columnname = 'text' then value end) as text,
       max(case when columnname = 'Start' then value end) as Start
from t
group by name;