3

我正在尝试在 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' 不是有效标识符。

我在这里想念什么?

4

3 回答 3

1

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

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

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

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;
于 2015-07-09T13:36:15.330 回答
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
于 2015-07-09T13:11:59.130 回答
0

你忘了关闭枢轴。

PIVOT(
        COUNT(Kundavtalid) 
        FOR YearMonth IN (' + @ColumnName + ') 
     ) AS PVTTable' -- here you miss pathernesis
于 2015-07-09T13:13:57.260 回答