2014-10-17 63 views
1

我想用Tsql將行轉換爲列,並消除空值。我該怎麼做呢?我當前的查詢:如何旋轉字幕?

IF OBJECT_ID(N'tempdb..#test_data') IS NOT NULL drop table #test_data 

create table #test_data (
question_caption varchar(max), 
[0] varchar(max), 
[1] varchar(max), 
[2] varchar(max), 
[3] varchar(max)) 

insert #test_data values('q1','abc',Null,Null,Null) 
insert #test_data values('q2',Null,'def',Null,Null) 
insert #test_data values('q3',Null,Null,'ghi',Null) 
insert #test_data values('q4',Null,Null,Null,'jkl') 

select * from #test_data 
pivot (
    Max([0]) 
    For question_caption in ([0],[1],[2],[3]) 
) as PivotTable 

輸出:

question_caption 0 1 2 3 
q1 abc NULL NULL NULL 
q2 NULL def NULL NULL 
q3 NULL NULL ghi NULL 
q4 NULL NULL NULL jkl 

我想要什麼:

q1 q2 q3 q4 
abc def ghi jkl 

我怎樣才能做到這一點?上面的查詢有錯誤: 消息265,級別16,狀態1,行4 在PIVOT運算符中指定的列名稱「0」與PIVOT參數中的現有列名稱衝突。

我嘗試了多個Pivot示例,但所有這些都導致了一個錯誤或另一個錯誤。

回答

1

你可以做一個簡單的max case

select [q1]=max(case when question_caption = 'q1' then [0] else null end), 
     [q2]=max(case when question_caption = 'q2' then [1] else null end), 
     [q3]=max(case when question_caption = 'q3' then [2] else null end), 
     [q4]=max(case when question_caption = 'q4' then [3] else null end) 
from #test_data 

或樞軸:

select [q1], [q2], [q3], [q4] 
from ( select question_caption, 
        coalesce([0],[1],[2],[3]) 
      from #test_data 
     ) s (c, v) 
pivot (max(v) for c in ([q1], [q2], [q3], [q4])) p