SQL Daily过去28天的滚动销售

问题描述

我在计算滚动销售时遇到了麻烦,我曾尝试使用powerpivot,但由于PC崩溃导致交易量大,所以我需要处理sql Server中的源查询

我每天需要一个新列,其中包含最近28天的销售总额,我每天按商品商店进行销售交易。

希望有人帮助我,谢谢。

Image

非常感谢, JR

解决方法

假设您想对按天和按Pos Qty分组的Item Nbr进行汇总,并且希望在最后28天中有28个不同的列,则查询看起来像这样:

select [Store...],[Item Nbr],sum(case when cast([Daily] as date) = cast(getdate() as date) then [POS Qty] end) SumDay0,sum(case when cast([Daily] as date) = cast(getdate() - 1 as date) then [POS Qty] end) SumDay_1,sum(case when cast([Daily] as date) = cast(getdate() - 2 as date) then [POS Qty] end) SumDay_2,sum(case when cast([Daily] as date) = cast(getdate() - 3 as date) then [POS Qty] end) SumDay_3,--...
       sum(case when cast([Daily] as date) = cast(getdate() - 27 as date) then [POS Qty] end) SumDay_27
 from [your table]
group by [Store...],[Item Nbr]

此查询为每个和使用case when语句,以便仅过滤您要查看的某一天的数据。然后总结case when语句的结果。

当然,如果您希望结果以行而不是列的形式出现,那么查询就需要以不同的方式编写。

,

如果每天都有数据,请使用窗口功能:

select t.*,sum(qty) over (partition by store,item order by daily rows between 27 preceding and current row) as avg_28day
from t;