2017-01-30 128 views
2

我是sql語言的新手,需要一些幫助來重新排列數據。替代樞軸

(我與SQL Server 2008工作),我有這個表(替補):

 
iteid | substitutedescr | substitutecode 
37664 | EANCUTIE3  | 14902778788926 
37664 | EAN1    | 4902778788929 
37664 | EANCUTIE1  | 4902778931653 
37664 | EANCUTIE2  | 4902778931738 

,我想一個選擇是這樣的:

 
iteid EAN1   EANCUTIE1   EANCUTIE2  EANCUTIE3 
37664              14902778788926 
37664 4902778788929   
37664     4902778931653  
37664          4902778931738 

我試圖使用數據透視:

select * 
from (
      select iteid as [ID], substitutedescr as [descr], substitutecode  as [Values] 
      from substitute) as s 
PIVOT 
(
SUM(SUBSTITUTECODE) 
FOR [DESCR] in (ean1, ean2, ean3, eancutie1, eancutie2, eancutie3) 
) as pvt 

但似乎我需要將兼容性級別設置爲更高的值才能激活樞軸功能。

我有其他替代方案來獲得此結果嗎?

謝謝。

回答

5

你不需要pivot對於這一點,只是case

select iteid, 
     (case when substitutedescr = 'EAN1' then substitutecode end) as EAN1, 
     (case when substitutedescr = 'EANCUTIE1' then substitutecode end) as EANCUTIE1, 
     (case when substitutedescr = 'EANCUTIE2' then substitutecode end) as EANCUTIE2, 
     (case when substitutedescr = 'EANCUTIE3' then substitutecode end) as EANCUTIE3 
from substitute; 

你想pivot(或集合),如果你想每iteid一行與該行的所有值。例如:

select iteid, 
     max(case when substitutedescr = 'EAN1' then substitutecode end) as EAN1, 
     max(case when substitutedescr = 'EANCUTIE1' then substitutecode end) as EANCUTIE1, 
     max(case when substitutedescr = 'EANCUTIE2' then substitutecode end) as EANCUTIE2, 
     max(case when substitutedescr = 'EANCUTIE3' then substitutecode end) as EANCUTIE3 
from substitute 
group by iteid; 
+0

謝謝你的回答:D解決了我的問題。 –