动态透视SQL Server 2012

时间:2015-07-09 13:07:18

标签: sql sql-server-2012 dynamic-pivot

我正在尝试在SQL Server 2012中运行我的第一个动态数据透视。

我用于动态旋转的#temp表看起来像这样。

YearMonth   Agreement nr    Discount
------------------------------------
201303         123            1
201303          12            0
201304           1            0

我正在运行此代码,但它不起作用:

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)

--Get distinct values of the PIVOT Column 
SELECT @ColumnName = ISNULL(@ColumnName + ',', '') + QUOTENAME(YearMonth )
FROM (SELECT DISTINCT YearMonth FROM #FINAL) AS Courses

--Prepare the PIVOT query using the dynamic 
SET @DynamicPivotQuery = 
  N'SELECT [Agreement nr],YearMonth , ' + @ColumnName + '
    FROM #FINAL
    PIVOT(
            COUNT(agreement nr) 
          FOR YearMonth IN (' + @ColumnName + ') AS PVTTable'
--Execute the Dynamic Pivot Query

EXECUTE  @DynamicPivotQuery;

我收到的错误消息是

  

FOR YearMonth IN([201403])AS PVTTable'不是有效的标识符。

我在这里缺少什么?

3 个答案:

答案 0 :(得分:1)

错误的原因是您在为数据透视设备别名之前错过了一个括号。不仅如此,你的支点效率还不高。

您应该在您的数据透视表中选择源表所需的内容,否则它可能会运行很长时间并产生大量具有空返回的行。

以下是固定的,希望更有效:

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)

--Get distinct values of the PIVOT Column 
SELECT @ColumnName= ISNULL(@ColumnName + ',','') 
       + QUOTENAME(YearMonth )
FROM (SELECT DISTINCT YearMonth FROM #FINAL) AS Courses

--Prepare the PIVOT query using the dynamic 
SET @DynamicPivotQuery = 
  N'SELECT ' + @ColumnName + '
    FROM (Select [Agreement nr], YearMonth from #FINAL) src
    PIVOT(
            COUNT([Agreement nr]) 
          FOR YearMonth IN (' + @ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query

EXECUTE sp_executesql @DynamicPivotQuery;

答案 1 :(得分:0)

您缺少一个括号

SET @DynamicPivotQuery = 
  N'SELECT [Agreement nr],YearMonth , ' + @ColumnName + '
    FROM #FINAL
    PIVOT(
            COUNT([agreement nr]) 
          FOR YearMonth IN (' + @ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query

答案 2 :(得分:0)

你忘了关闭枢轴。

PIVOT(
        COUNT(Kundavtalid) 
        FOR YearMonth IN (' + @ColumnName + ') 
     ) AS PVTTable' -- here you miss pathernesis