【发布时间】:2021-09-11 22:38:57
【问题描述】:
我正在尝试计算 6 周内的滚动平均值,其中我在特定时间范围内放弃了高销售周和低销售周。
我使用 windows 函数来确定销售高峰和低谷周,但我无法在 6 周窗口内运行平均值并排除高低。
我尝试在 avg 函数中使用 case 语句,但它返回了错误的结果。
这是我的代码:
;with average_daily_sales
as
(
select sum(SalesUnits) as total_sales_units,
ItemNumber,
Store,
END_OF_WEEK,
BEGIN_OF_WEEK
from CONFORM_MOVEMENT
where Store = 10 and ItemNumber =1026295
group by ItemNumber, Store, END_OF_WEEK, BEGIN_OF_WEEK
)
--USING windows function to accomplish a 6 week rolling average to identify the high and low selling weeks
--PARTITION BY creates pairs of stores and item numbers to analyze per each window (6 records represent 6 weeks)
--Set the window being analyzed by replacing the integer value between "ROWS BETWEEEN N PRECEEDING"
,highs_lows_identifier
as
(
select
max(total_sales_units)
over (PARTITION BY Store, ItemNumber ORDER BY END_OF_WEEK
ROWS BETWEEN 5 PRECEDING AND CURRENT ROW ) as highs,
min(total_sales_units)
over (PARTITION BY Store, ItemNumber ORDER BY END_OF_WEEK
ROWS BETWEEN 5 PRECEDING AND CURRENT ROW ) as lows,
Store,
ItemNumber,
END_OF_WEEK,
BEGIN_OF_WEEK,
total_sales_units
from average_daily_sales
group by Store, ItemNumber, END_OF_WEEK, BEGIN_OF_WEEK, total_sales_units
)
--Remove highs and lows from their respective record
,remove_highs_and_lows
as
(
select
avg(case when total_sales_units = highs
or total_sales_units = lows
then null else total_sales_units end)
over ( partition by Store, ItemNumber ORDER BY END_OF_WEEK
rows between 5 preceding and current row) as average_sales_units,
Store,
ItemNumber,
BEGIN_OF_WEEK,
END_OF_WEEK,
highs,
lows,
total_sales_units,
total_sales_units /7 as daily_sales_units
from highs_lows_identifier
)
select * from remove_highs_and_lows
order by END_OF_WEEK asc
结果图片:
预期:记录 19 中的 average_sales_units 应为 61.5(不包括记录 16 和 17)。但是,没有发生排除,我的结果是 64。这个逻辑应该出现在每条记录中(例如记录 18 average_sales_units 应该排除记录 16 和 13)。
任何建议都会很棒!
谢谢
【问题讨论】:
-
样本数据和期望的结果真的很有帮助。
-
嗨@GordonLinoff 我应该附上一个包含数据和结果的excel文件吗?抱歉,最后的图片和解释就足够了
-
。 .不,您应该将几行示例数据作为文本表添加到问题中。
-
根据问题指南,请不要发布代码、数据、错误消息等的图像 - 将文本复制或输入到问题中。请保留将图像用于图表或演示渲染错误,无法通过文本准确描述的事情。
标签: sql sql-server window-functions rolling-computation