我想拆分的列有很多值:
Col1 Col2
val1 stuff
val2 stuff
val3 stuff
val4 stuff
.... .....
预期产出:
val1 val2 val3 val4 ....
stuff stuff stuff stuff
我尝试了pivot方法,但由于我的列有很多值,所以我不知道如何调整它并让它工作。
答案 0 :(得分:0)
请尝试:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.Col1)
FROM t c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT ' + @cols + ' from
(
select *
from t
) x
pivot
(
min(Col2)
for Col1 in (' + @cols + ')
) p '
execute(@query)