将列拆分为多个列

时间:2013-10-04 09:31:00

标签: sql sql-server-2008-r2

我想拆分的列有很多值:

Col1   Col2

val1   stuff
val2   stuff
val3   stuff
val4   stuff
....   .....

预期产出:

val1   val2  val3  val4   ....
stuff  stuff stuff stuff

我尝试了pivot方法,但由于我的列有很多值,所以我不知道如何调整它并让它工作。

1 个答案:

答案 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)

SQL Fiddle Demo