簡體   English   中英

如何在列名稱為SQL Server的SQL Server中返回數據透視表?

[英]How can i return Pivot table in sql server with column name?

我已經檢查過發布的問題,它基於結果而不是基於列名進行數據透視,請問sql腳本應該檢索什么結果?

實際結果

在此處輸入圖片說明

預期結果

預期結果

先感謝您。

您可以使用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;

然后,您可以使用動態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);

Chanage #t根據您的情況)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM