SQL Server : calculate monthly total sales incl empty months

后端 未结 2 1065
抹茶落季
抹茶落季 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)
    
    0 讨论(0)
  • 2021-01-22 04:06

    Try:

    ;with CTE as 
    (select 0 months_ago union all 
     select months_ago - 1 months_ago from CTE where months_ago > -11),
    month_list as 
    (select dateadd(MONTH, 
                    months_ago, 
                    dateadd(DAY, 
                            1-datepart(DAY,getdate()),
                            cast(GETDATE() as DATE))) month_start 
     from cte)
    SELECT YEAR(ml.start_date) as 'Year', 
           MONTH(ml.start_date) as 'Month', 
           sum(Amount) as 'Units sold',[ProductNo]
    FROM month_list ml
    left join [Order] o 
           on o.OrderDate >= ml.start_date and 
              o.OrderDate < dateadd(MONTH, 1, ml.start_date)
    left join [OrderLine] ol 
           on ol.OrderNo = o.OrderNo and ProductNo = @ProductNo
    Group by ProductNo, YEAR(ml.start_date), Month(ml.start_date)
    Order by ProductNo, YEAR(ml.start_date), Month(ml.start_date)
    
    0 讨论(0)
提交回复
热议问题