我有这样的表:
表1: ID Varible_Name
1 abc
1 pqr
1 xyz
我需要这种方式。 表2:
ID abc pqr xyz
1 235 345 567
2 456 788 090
3 567 454 908
答案 0 :(得分:0)
您可以像这样使用动态PIVOT
:
CREATE TABLE #TempTable
([ID] int, [Varible_Name] varchar(3), amount int)
INSERT INTO #TempTable
([ID], [Varible_Name],amount)
VALUES
(1, 'abc',235),
(1, 'pqr',345),
(1, 'xyz',567),
(2, 'abc',456),
(2, 'pqr',788),
(2, 'xyz',090),
(3, 'abc',567),
(3, 'pqr',454),
(3, 'xyz',908)
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME([Varible_Name])
from #TempTable
group by [Varible_Name]
order by [Varible_Name]
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT [ID],' + @cols + ' from
(
select [ID], [Varible_Name], [amount]
from #TempTable
) x
pivot
(
sum([amount])
for [Varible_Name] in (' + @cols + ')
) p '
execute(@query);
<强>结果:强>
ID abc pqr xyz
1 235 345 567
2 456 788 90
3 567 454 908
注意:如果要将结果集保存到临时表,可以使用INTO
表并修改@query
之类的
set @query = 'SELECT [ID],' + @cols + 'into ##TempTbl2 from
(
select [ID], [Varible_Name], [amount]
from #TempTable
) x
pivot
(
sum([amount])
for [Varible_Name] in (' + @cols + ')
) p '
select * from ##TempTbl2