SQL Server : calculate monthly total sales incl empty months

后端 未结 2 1064
抹茶落季
抹茶落季 2021-01-22 03:16

I\'m trying to calculate the total sales of a product in a month, but I would like it to include any \"empty\" months (with no sales) and only select the latest 12 months.

2条回答
  •  隐瞒了意图╮
    2021-01-22 03:59

    I've done before I know that you have calendar table. I've used master.dbo.spt_values to generate last twelve consecutive months (including current).

        declare @ProductNo int
    
        set @ProductNo = 1234
    
    select MONTH(d.date), YEAR(d.date), isnull(t.amnt, 0) as [Units sold] from (
        SELECT
            YEAR(o.OrderDate) as 'Year', 
            MONTH(o.OrderDate) as 'Month', 
            sum(Amount) as amnt,
            [ProductNo]
        FROM [OrderLine] ol
        inner join [Order] o on ol.OrderNo = o.OrderNo
        where ProductNo = @ProductNo
        group by ProductNo, YEAR(o.OrderDate), Month(o.OrderDate)
    ) t
    right join (
        select dateadd(mm, -number, getdate()) as date
        from master.dbo.spt_values 
        where type = 'p' and number < 12
    ) d  on year(d.date) = t.[year] and month(d.date) = t.[month]
    order by YEAR(d.date), MONTH(d.date)
    

提交回复
热议问题