动态数据透视表

时间:2017-03-08 17:38:06

标签: sql-server dynamic pivot

我正在尝试动态地执行多个数据透视表,每次都使用水平列值。

我尝试执行以下查询,但由于某种原因它失败了,即使我打印查询并随后执行它,一切正常。

DECLARE @sql VARCHAR(MAX) = (
SELECT ' SELECT '+ QUOTENAME(c.name)
    + '
      ,[1] AS a
      ,[2] AS b
      ,[3] AS c
FROM 
    (SELECT [ID]
            ,CASE WHEN [c1] < 25 THEN 1
              ELSE CASE WHEN [c1] < 45 THEN 2
              ELSE 3 END END AS cat
            ,' + QUOTENAME(c.name) + '
    FROM [dbo].[table]) p
PIVOT
(
COUNT (ID)
FOR cat IN ([1], [2], [3] )
) AS pvt
ORDER BY [2] desc
'
FROM sys.columns c
    WHERE c.object_id = OBJECT_ID('dbo.SAMR_respons')
    AND c.name NOT IN ('ID')
    FOR XML PATH('')
)

PRINT(@sql)
EXEC(@sql);

有谁知道可能出现什么问题? 我得到的错误是:

Msg 102, Level 15, State 1, Line 2
Incorrect syntax near ','.
Msg 102, Level 15, State 1, Line 6
Incorrect syntax near ';'.

0 个答案:

没有答案