[英]How can i return Pivot table in sql server with column name?
您可以使用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.