我正在尝试在 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' 不是有效标识符。
我在这里想念什么?