-3

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

4

1 回答 1

2

为了获得最终结果,您可以使用 PIVOT 函数,但首先我会取消旋转您的col1col2列,这样您就不会有多个列可以旋转。

如果您的列数有限,则可以对查询进行硬编码:

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;

但是如果你有未知数量的sequence值,那么你可以使用动态 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;
于 2013-10-16T15:36:32.363 回答