gpt4 book ai didi

SQL Server : calculate monthly total sales incl empty months

转载 作者:行者123 更新时间:2023-12-04 05:54:12 27 4
gpt4 key购买 nike

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

最佳答案

在我知道你有日历表之前我已经做了。我用过 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)

关于SQL Server : calculate monthly total sales incl empty months,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9715676/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com