I am getting the error message - Msg 102, Level 15, State 1, Line 5 Incorrect syntax near ','. when I run the below query. I can't figure out why the syntax is incorrect. Does anyone have any suggestions?
DECLARE @Vendor AS INT = 41
CREATE TABLE #PivotData
(
[ID] INT,
[Row] VARCHAR(MAX),
[Columns] VARCHAR(MAX),
[AggData] INT
)
INSERT INTO #PivotData
SELECT V.Vendor_Key
,O.Location_Desc
,P.Item_Desc
,IIF.Sales_Qty
FROM PDI.PDI_Warehouse_952_01.dbo.Item_Inventory_Fact IIF
INNER JOIN PDI.PDI_Warehouse_952_01.dbo.Item_Purchases_Fact IPF
ON IIF.Calendar_Key = IPF.Calendar_Key
AND IIF.Organization_Key = IPF.Organization_Key
AND IIF.Product_Key = IPF.Product_Key
INNER JOIN PDI.PDI_Warehouse_952_01.dbo.Organization O
ON IIF.Organization_Key = O.Organization_Key
INNER JOIN PDI.PDI_Warehouse_952_01.dbo.Product P
ON IIF.Product_Key = P.Product_Key
INNER JOIN PDI.PDI_Warehouse_952_01.dbo.Vendor V
ON IPF.Vendor_Key = V.Vendor_Key
WHERE V.Vendor_key = @Vendor
DECLARE @Cols AS NVARCHAR(MAX),
@Query AS NVARCHAR(MAX)
SET @Cols = STUFF ((SELECT DISTINCT ',' + QUOTENAME(P.Columns)
FROM #PivotData P
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET @Query = 'SELECT Row, ' + @Cols + ' FROM
(
SELECT Row
,Column
,Aggregate
FROM #PivotData
)x
PIVOT
(
SUM(Aggregate)
FOR Row IN (' + @Cols + ')
) p '
EXECUTE(@Query)
DROP TABLE #PivotData
Aucun commentaire:
Enregistrer un commentaire