Sql Server Group by和Case When

时间:2015-09-02 10:05:33

标签: sql-server-2012 group-by case

假设我们有这个表内容:

id  type  value
1    A    X1122
1    B    JJHJU
2    A    POIUY
2    C    YUHGF

我希望通过选择获得此解决方案:

id  valueA  valueB  valueC
1   X1122   JJHJU   NULL
2   POIUY   NULL    YUHGF

我的第一次尝试是:

SELECT id, CASE type WHEN A THEN value ELSE NULL END AS valueA
, CASE type WHEN B THEN value ELSE NULL END AS valueB
, CASE type WHEN C THEN value ELSE NULL END AS valueC
FROM table
GROUP BY id

但它返回错误

  

列'类型'和'价值'需要在GROUP BY语句中

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

你想要达到的目标叫做PIVOT:

FocusedRecordIndex

输出:

declare @data table(id int, valtype char(1), val varchar(10))
insert into @data(id, valtype, val) values
(1, 'A', 'X1122'), (1, 'B', 'JJHJU'), (2, 'A', 'POIUY'), (2, 'C', 'YUHGF')

Select id, valueA = piv.A, valueB = piv.B, valueC = piv.C
From @data
Pivot ( 
    max(val)
    for valtype in ([A], [B], [C])
) as piv

technet

上的PIVOT