SELECT [Table], Facility_Code,
ISNULL([1],0) AS [1],
ISNULL([2],0) AS [2],
ISNULL([3],0) AS [3],
ISNULL([4],0) AS [4],
ISNULL([5],0) AS [5],
ISNULL([6],0) AS [6],
ISNULL([7],0) AS [7],
ISNULL([8],0) AS [8],
ISNULL([9],0) AS [9],
ISNULL([10],0) AS [10],
ISNULL([11],0) AS [11],
ISNULL([12],0) AS [12],
FROM(
SELECT 'TotalItemsProduced' AS [Table],
L.Facility_Code,
[Month],
Total_Item_Count
FROM production L
LEFT JOIN(
SELECT
Facility_Code,
COUNT(DISTINCT(item_nbr)) AS Total_Item_Count,
MONTH(datetime) AS MONTH
FROM item
WHERE YEAR(datetime) = 2018
GROUP BY Facility_Code, MONTH(datetime)
)R
ON L.Facility_Code = R.Facility_Code
)T
PIVOT(MAX(Total_Item_Count) FOR [Month] IN ([1], [2], [3], [4], [5], [6],
[7], [8], [9], [10], [11], [12])) AS PVT
我写了这段代码,到此为止,现在我必须取消透视表。我不确定如何嵌套在unpivot函数中,因为左联接有点让我失望。