SQL 组和按月求和 - 默认为零
我目前正在按月对库存使用情况进行分组和求和:
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
I am currently grouping and summing inventory usage by month:
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)
This gives me the results that I'm expecting:
ItemID Kit_MonthQty Kit_MonthAsNumber Kit_MonthAsString
13188 234 8 August
13188 45 9 September
13188 61 10 October
13188 20 12 December
Question
What must I do to return zero for months where no data exsits, like this:
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在过去,我通过创建一个临时表来解决这样的问题,该表将保存所需的所有日期:
然后,修改您的查询以加入该表:
然后您应该有每个月的记录,无论它是否存在在库存中。
In the past, I've solved a problem like this by creating a temporary table which will hold all dates needed:
Then, modify your query to join against this table:
Then you should have a record for each month, regardless of whether it exists in Inventory.
您可以像这样准备一个“日历”表:
然后在月份和年份日期部分对表进行
LEFT JOIN
。这样,您将始终将开始日期和结束日期之间的所有月份作为行。You could prepare a 'calendar' table like so:
and then do a
LEFT JOIN
with your table on the month and year date parts. This way you'll always have all the months between the start and end date as rows.这是一种方法。这假设
@StartRange
和@EndRange
属于同一日历年,否则您会得到一些有趣的结果。Here's one way. This assumes that
@StartRange
and@EndRange
fall within the same calendar year, otherwise you will get some funny results.