1

我要拆分的列有很多值:

Col1   Col2

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

预期输出:

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

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

4

1 回答 1

0

Please try:

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

于 2013-10-04T09:56:30.317 回答