2017-05-30 83 views

回答

0

你可以用union all做到這一點:

select 'name' as which, 
     max(case when id = 1 then name end) as [1], 
     max(case when id = 2 then name end) as [2], 
     max(case when id = 3 then name end) as [3], 
     max(case when id = 4 then name end) as [4] 
from t 
union all 
select 'state' as which, 
     max(case when id = 1 then state end) as [1], 
     max(case when id = 2 then state end) as [2], 
     max(case when id = 3 then state end) as [3], 
     max(case when id = 4 then state end) as [4] 
from t; 
+0

將會有840列,我不能像這樣使用 – Rahul

+0

然後你需要創建一個動態創建這個的存儲過程。你會有一個你用+1增加的變量,以便你有id = 1,id = 2 ... id = n。這個方法有一個很好的教程:https://www.mssqltips.com/sqlservertip/1160/execute-dynamic-sql-commands-in-sql-server/微軟也提供了一些基本的指令:https:// docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-executesql-transact-sql 否則,Gordon Linoff所示的方法是正確的。 – ksauter

0

然後,您可以使用動態SQL查詢。

查詢

declare @sql as varchar(max); 

select @sql = 'select '+ char(39) + 'name' + char(39) + ' as [id],' + 
stuff((select distinct ', max(case when [id] = ' 
    + cast([id] as varchar(100)) + ' then [name] end) 
     as [' + cast([id] as varchar(100)) + ']' 
    from #t 
    for xml path('') 
), 1, 2, '') + 
' from #t union all ' + 
'select '+ char(39) + 'state' + char(39) + ' as [id],' + 
stuff((select distinct ', max(case when [id] = ' 
    + cast([id] as varchar(100)) + ' then [state] end) 
     as [' + cast([id] as varchar(100)) + ']' 
    from #t 
    for xml path('') 
), 1, 2, '') + 
' from #t'; 

exec(@sql); 

#t Chanage根據你的。

+0

我有840多列,我不能在你的查詢中單獨編寫它們中的每一個,有沒有其他方法可以自動獲得結果的列名並進行迭代? – Rahul

+0

@Rahul:在這裏你不需要單獨寫他們。它是動態的。首先嚐試使用此查詢,然後進行評論。不要盲目評論。 – Wanderer

+0

在這裏你已經使用ID和名稱靜態內查詢,我不需要把 (「最大(案件當[id] ='+ cast([id]作爲varchar(100))+'然後[名稱]」)。 – Rahul

相關問題