SQL Group and Sum By Month - Default to Zero

后端 未结 3 588
独厮守ぢ
独厮守ぢ 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 03:56

    In the past, I've solved a problem like this by creating a temporary table which will hold all dates needed:

        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
    

    Then, modify your query to join against this table:

    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
    

    Then you should have a record for each month, regardless of whether it exists in Inventory.

提交回复
热议问题