答案 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
根据你的说法。