问题
Hi I am trying in SQL Server the pivoting for the following table
REFID | COL1 | COL2 | Sequence
1       abc    cde     1
1       lmn    rst     2
1       kna    asg     3
2       als    zkd     2
2       zpk    lad     1
I want the output as
   COLNAME REFID | 1 | 2 | 3
     COL1   1     abc lmn kna
     COL2   1     cde rst asg
     COL1   2     zpk als null
     COL2   2     lad zkd null
The number of columns in the original table are known but the number of rows are not known. Can any one help
回答1:
In order to get the final result, you can use the PIVOT function but first I would unpivot your col1 and col2 columns so you won't have multiple columns to pivot.
If you have a limited number of columns, then you can hard-code the query:
select REFID, col, [1], [2], [3]
from 
(
    select REFID, Sequence, col, value
    from yourtable
    cross apply
    (
        select 'COL1', col1 union all
        select 'COL2', col2
    ) c (col, value)
) d
pivot
(
    max(value)
    for sequence in ([1], [2], [3])
) piv
order by refid;
But it you have an unknown number of sequence values, then you can use dynamic SQL:
DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(sequence) 
                    from yourtable
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
set @query = 'SELECT refid, col,' + @cols + ' 
            from 
            (
                select REFID, Sequence, col, value
                from yourtable
                cross apply
                (
                    select ''COL1'', col1 union all
                    select ''COL2'', col2
                ) c (col, value)
            ) x
            pivot 
            (
                max(value)
                for Sequence in (' + @cols + ')
            ) p 
            order by refid'
execute sp_executesql @query;
来源:https://stackoverflow.com/questions/19407091/sql-complex-dynamic-pivoting