SQL Server : calculate monthly total sales incl empty months

旧城冷巷雨未停 提交于 2019-12-02 04:39:35

问题


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.

This is my code so far.

declare
@ProductNo int

set @ProductNo = 1234

SELECT 
YEAR(o.OrderDate) as 'Year', MONTH(o.OrderDate) as 'Month', sum(Amount) as 'Units sold',[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)
  Order by ProductNo, YEAR(o.OrderDate), Month(o.OrderDate)

This returns

Year    Month   Units sold
2011    6       2
2011    10      1
2011    11      1
2012    2       1

But I would like it to return.

Year    Month   Units sold
2011    4       0
2011    5       0
2011    6       2
2011    7       0
2011    8       0    
2011    9       0
2011    10      1
2011    11      1
2011    12      0
2012    1       0
2012    2       2
2012    3       0

I'm using SQL Server 2008 R2 Sp1


回答1:


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)



回答2:


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)


来源:https://stackoverflow.com/questions/9715676/sql-server-calculate-monthly-total-sales-incl-empty-months

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!