如何在列号名称的SQL Server中返回Pivot表?

时间:2017-05-30 11:37:16

标签: sql sql-server sql-server-2008

我已根据结果而非基于列名称检查了发布的问题 能不能请一下sql脚本检索这个结果的建议?

实际结果

enter image description here

预期结果

Expected Result

提前谢谢你。

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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);

Chanage #t根据你的说法。