SQL Group and Sum By Month - Default to Zero

后端 未结 3 595
独厮守ぢ
独厮守ぢ 2020-12-12 03:32

I am currently grouping and summing inventory usage by month:

SELECT      Inventory.itemid AS ItemID,
            SUM(Inventory.Totalunits) AS Individual_Mon         


        
3条回答
  •  孤街浪徒
    2020-12-12 04:05

    You could prepare a 'calendar' table like so:

    DECLARE @d datetime
    SET @d = @StartRange
    
    DECLARE @calendar TABLE (Date datetime)
    
    WHILE (@d <= @EndRange) BEGIN
        INSERT INTO @Calendar VALUES (@d)
        SET @d = DATEADD(month, 1, @d)
    END
    

    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.

提交回复
热议问题