SQL Server : calculate monthly total sales incl empty months

后端 未结 2 1077
抹茶落季
抹茶落季 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 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)
    

提交回复
热议问题