可能重复:
如何从动态数据透视表中分配普通表?
我有这个查询:
DECLARE @Col NVARCHAR(MAX) =
( SELECT ', ' + QUOTENAME(CONVERT(VARCHAR, DATEADD(MONTH, DATEDIFF(MONTH, 0, CURRENT_TIMESTAMP) - (12 - Number), 0), 103)) + ' = [' + CAST(number AS VARCHAR) + ']'
FROM Master..spt_values
WHERE Type = 'P'
AND number BETWEEN 0 AND 12
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
DECLARE @SQL NVARCHAR(MAX) =
N'WITH Data AS
( SELECT DACP_Id, DACP_Value, ResultCenters.RSL_CodDescr AS CentroResultado, Users.USR_EmpName Colaborador, Devices.DEV_NoArea+Devices.DEV_No as AreaNumero,
[MonthNum] = 12 - DATEDIFF(MONTH, DACP_Date, CURRENT_TIMESTAMP)
FROM DevicesAccompaniments INNER JOIN
Devices ON Devices.DEV_Id = DevicesAccompaniments.FK_DEV_Id INNER JOIN
ResultCenters ON ResultCenters.RSL_Id = Devices.DEV_RsltId INNER JOIN
Contracts ON Contracts.CNT_Id = Devices.DEV_ContrId INNER JOIN
Users ON Users.USR_Id = Devices.DEV_UsrId
WHERE DATEDIFF(MONTH, DACP_Date, CURRENT_TIMESTAMP) BETWEEN 0 AND 12
)
SELECT CentroResultado, Colaborador, AreaNumero' + @Col + '
FROM Data
PIVOT
( SUM(DACP_Value)
FOR MonthNum IN ([0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12])
) pvt;'
它创建了 12 列和关于我们当前日期过去 12 个月的附加信息,问题是我需要将此查询放入报告中,但我需要将列映射到带有 var @SQL 中的信息的临时表中,而不仅仅是执行'EXEC sp_executesql @SQL;' 这是从当前日期起过去 12 个月的示例小提琴:http ://www.sqlfiddle.com/#!3/3205a/14
欢迎任何帮助,谢谢。