我目前正在按月对库存使用情况进行分组和汇总:
SELECT Inventory.itemid AS ItemID, SUM(Inventory.Totalunits) AS Individual_MonthQty, MONTH(Inventory.dadded) AS Individual_MonthAsNumber, DATENAME(MONTH, Inventory.dadded) AS Individual_MonthAsString FROM Inventory WHERE Inventory.invtype = 'Shipment' AND Inventory.dadded >= @StartRange AND Inventory.dadded <= @EndRange GROUP BY Inventory.ItemID, MONTH(Inventory.dadded), DATENAME(MONTH, Inventory.dadded)
这给了我期望的结果:
ItemID Kit_MonthQty Kit_MonthAsNumber Kit_MonthAsString 13188 234 8 August 13188 45 9 September 13188 61 10 October 13188 20 12 December
问题
在没有数据存在的月份中,我该怎么做才能返回 零 ,如下所示:
ItemID Kit_MonthQty Kit_MonthAsNumber Kit_MonthAsString 13188 0 1 January 13188 0 2 February 13188 0 3 March 13188 0 4 April 13188 0 5 May 13188 0 6 June 13188 0 7 July 13188 234 8 August 13188 45 9 September 13188 61 10 October 13188 0 11 November 13188 20 12 December
过去,我通过创建一个临时表来解决这样的问题,该表将保存所有需要的日期:
CREATE TABLE #AllDates (ThisDate datetime null) SET @CurrentDate = @StartRange -- insert all dates into temp table WHILE @CurrentDate <= @EndRange BEGIN INSERT INTO #AllDates values(@CurrentDate) SET @CurrentDate = dateadd(mm, 1, @CurrentDate) END
然后,修改查询以针对该表进行联接:
SELECT ALLItems.ItemId, SUM(COALESCE(Inventory.Qty, 0)) AS Individual_MonthQty, MONTH(#AllDates.ThisDate) AS Individual_MonthAsNumber, DATENAME(MONTH, #AllDates.ThisDate) AS Individual_MonthAsString FROM #AllDates JOIN (SELECT DISTINCT dbo.Inventory.ItemId FROM dbo.Inventory) AS ALLItems ON 1 = 1 LEFT JOIN Inventory ON DATEADD(dd, - DAY(Inventory.dadded) +1, Inventory.dadded) = #AllDates.ThisDate AND ALLItems.ItemId = dbo.Inventory.ItemId WHERE #AllDates.ThisDate >= @StartRange AND #AllDates.ThisDate <= @EndRange GROUP BY ALLItems.ItemId, #AllDates.ThisDate
然后,无论库存中是否存在该记录,您都应该有每个月的记录。