小编典典

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

sql

我正在尝试计算一个月内某个产品的总销售额,但是我希望它包括所有“空”月(无销售),并且只选择最近的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


阅读 353

收藏
2021-04-14

共1个答案

小编典典

在知道您有日历表之前,我已经做完了。我已经习惯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)
2021-04-14