SQL Server:计算每月总销售额,包括空月

时间:2012-03-15 07:46:22

标签: sql sql-server-2008-r2

我正在尝试计算一个月内产品的总销售额,但我希望它包括任何“空”月(没有销售),只选择最近12个月。

到目前为止,这是我的代码。

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)

返回

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

但我希望它能够回归。

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

我正在使用SQL Server 2008 R2 Sp1

2 个答案:

答案 0 :(得分:2)

在我知道你有日历表之前我已经完成了。我已经使用master.dbo.spt_values连续十二个月生成(包括当前)。

    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)

答案 1 :(得分:1)

尝试:

;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)