Window 运行超过 30 天但缺少行

Window function over 30 days but missing rows

除了每天售出的数量外,我还试图获得 运行 每种产品在过去 30 天内售出的总数。我尝试在前一行和当前行之间使用 window 函数来执行此操作,但问题是产品并不总是每天都在销售,所以我的 window 函数正在回顾 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 天。有什么方法可以完成我想做的事情吗?

谢谢

如果您设置 window 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

如果您设置 window 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

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

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

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 的回答中得到了相同的结果:)。