动态旋转 SQL Server 2012

Dynamic pivoting SQL Server 2012

我正在尝试 运行 我在 SQL Server 2012 中的第一个动态枢轴。

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

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' is not a valid identifier.

我在这里错过了什么?

你少了一个括号

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

您忘记关闭数据透视表。

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

错误的原因是您在为 Pivot 设置别名之前缺少括号。不仅如此,您的支点效率还很低。

你应该 select 你需要的源 table 在你的数据透视表中,否则它可能会 运行 很长一段时间并产生很多空行 returns.

以下已修复,希望更有效:

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;