带有指定值的SQL Pivot

时间:2013-08-20 19:28:07

标签: sql-server sql-server-2008 tsql pivot

我想设置一个如下所示的数据透视表,但不是传递列值,而是希望它返回全部;我想把括号底部留空(即Sum(fldNI)FOR fldCI IN()....

SELECT * 
    FROM    
(
    SELECT fldPK
          ,fldFPK
          ,fldNI
          ,fldCI
    FROM qryOne 
) as x
PIVOT
(
    Sum(fldNI) FOR fldCI IN ()
) as p

1 个答案:

答案 0 :(得分:0)

当您使用PIVOT函数时,必须知道这些值才能将它们转换为列。如果您不提前知道这些值,则必须实现动态SQL才能获得结果。动态SQL代码将创建将转换为列的值列表,然后将此列表连接到执行的查询字符串。

代码类似于:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(fldCI) 
                    from qryOne
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT fldPK, fldFPK, ' + @cols + ' 
            from 
            (
               SELECT fldPK
                    ,fldFPK
                    ,fldNI
                    ,fldCI
              FROM qryOne 
            ) x
            pivot 
            (
                sum(fldNI)
                for fldCI in (' + @cols + ')
            ) p '

execute sp_executesql @query