窗口功能超过30天但缺少行

时间:2017-01-11 01:55:55

标签: sql-server date window-functions

除了每天销售的产品数量之外,我还试图了解过去30天内每种产品的销售量。我尝试使用前一行和当前行之间的窗口函数来执行此操作,但问题是产品并不总是每天都进行销售,所以我的窗口函数回顾了30行而不是30天。

示例数据如下:

date       | prod_id | sales | wrong_answer | correct_answer
2016-09-22   123       5       5              5
2016-09-24   123       2       7              7
2016-09-30   123       5       12             12
2016-10-01   123       4       16             16
2016-10-06   123       6       22             22
2016-10-18   123       4       26             26
2016-10-20   123       6       32             32
2016-11-04   123       14      46             30
2016-11-05   123       40      86             70
2016-11-25   123       30      116            94
2016-11-26   123       9       125            103
2016-12-10   123       12      137            115
2016-12-12   123       8       145            123
2016-12-16   123       4       149            127
2016-12-31   123       3       152            130
2017-01-09   123       4       156            134
2016-09-22   456       etc     etc            etc

我的查询是:

SELECT
  date,
  prod_id,
  sales,
  SUM(sales) OVER (PARTITION BY prod_id OVER BY date ASC ROWS BETWEEN 30 PRECEDING AND CURRENT ROW) as wrong_answer
FROM prod_sales

正如您所看到的,当日期达到2016-11-04时,wrong_answer仍然会回顾30行而不是30天。有没有办法完成我想要做的事情?

由于

2 个答案:

答案 0 :(得分:1)

如果您设置30天的窗口..

 select t1.[date], t1.prod_id, t1.sales, 
(select distinct sum(sales) over(order by prod_id)
from prod_sales as t2 where 
t2.date<= t1.date and t2.date > dateadd(day,-30,t1.date) and t2.prod_id = t1.prod_id) 
from prod_sales as t1

如果您设置1个月的窗口..

select t1.[date], t1.prod_id, t1.sales, 
(select distinct sum(sales) over(order by prod_id)
from prod_sales as t2 where 
t2.date<= t1.date and t2.date > dateadd(month,-1,t1.date) and t2.prod_id = t1.prod_id) 
from prod_sales as t1

注意:与正确答案略有不同...如果我没有正确回答您的问题,请纠正我。

答案 1 :(得分:0)

这是一篇很老的帖子,但我想在子查询中聚合也可以:

select t1.`date`, t1.prod_id, t1.sales,
   # use subquery to aggregate
(
    select sum(sales)
    from sample_sales as t2
    where subdate(t1.date, 30) < t2.date and t2.date<= t1.date and t2.prod_id = t1.prod_id
) sales_30_days
from sample_sales as t1;

至少我从 Pramod 的回答中得到了相同的结果:)