2015-09-02 63 views
-1

假設我們有這個表的內容:SQL Server組通過與案例當

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語句

什麼建議嗎?

回答

0

什麼你正在努力實現被稱爲PIVOT:

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 

輸出:

1 X1122 JJHJU NULL 
2 POIUY NULL YUHGF 

PIVOT上technet