Sql-Server
當某些月份在表中沒有記錄時如何獲取最近 12 個月的值
我有一個表,其中 PartNumberKey 和 Depot_ID 作為複合主鍵。它返回以下數據 -
要求是添加過去 12 個月(即從 2018-11 到 2018-12)中沒有 0 行的月份列作為 Total。預期的輸出應該是:
請幫我查詢形成?
從一個數字表開始,然後你可以用它
dateadd
來製作一個月份表。然後你就可以left join
了。如果您沒有數字表格,則可以
ROW_NUMBER
在足夠大的表格上使用。SELECT TOP (DATEDIFF(month, @month1, @month2)+1) DATEADD(month, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) -1, @month1) AS TheMonth FROM dbo.MyTable
您還需要您的 PartNumberKey 和 Depot_ID 值列表。
DECLARE @month1 date = ‘20171201’, @month2 date = ‘20181101’; -- the semicolon is important!! WITH months as ( SELECT TOP (DATEDIFF(month, @month1, @month2)+1) DATEADD(month, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) -1, @month1) AS TheMonth FROM dbo.MyTable ), PartsDepots as ( SELECT DISTINCT PartNumberKey, Depot_ID FROM dbo.MyTable ) SELECT pd.PartNumberKey, pd.Depot_ID, m.TheMonth, COUNT(*) AS Total FROM months m CROSS JOIN PartsDepots pd LEFT JOIN dbo.MyTable t ON t.TheDate >= m.TheMonth AND t.TheDate < DATEADD(month,1,m.TheMonth) AND t.PartNumberKey = pd.PartNumberKey AND t.Depot_ID = pd.Depot_ID GROUP BY t.TheMonth, pd.PartNumberKey, pd.Depot_ID ;