SQL:过去 30 天内按组滚动总和

All*_*len 3 sql amazon-redshift

我有一张如下表:

date, custid, sales
2015-01-01, 01, 100
2015-01-10, 01, 200
2015-02-05, 01, 300
2015-03-02, 01, 400
2015-03-03, 01, 500
2015-01-01, 02, 100
2015-01-10, 02, 200
2015-02-05, 02, 300
2015-03-02, 02, 400
2015-03-03, 02, 500
...
Run Code Online (Sandbox Code Playgroud)

如何按日期和 custid 生成过去 30 天的滚动销售总额。

所需的输出是:

date, custid, running_30_day_sales
2015-01-01, 01, 100
2015-01-10, 01, 300 --(100+200)
2015-02-05, 01, 500 --(200+300)
2015-03-02, 01, 700 --(300+400)
2015-03-03, 01, 1200 -- (300+400+500)
2015-01-01, 02, 100
2015-01-10, 02, 300 --(100+200)
2015-02-05, 02, 500 --(200+300)
2015-03-02, 02, 700 --(300+400)
2015-03-03, 02, 1200 -- (300+400+500)
Run Code Online (Sandbox Code Playgroud)

Vam*_*ala 6

这是使用self join. 每个日期与所有日期差异>0且<=30的日期连接。此后,它只是一个分组操作。

select a1.custid, a1.dt, a1.sales+sum(coalesce(a2.sales,0)) total
from atable a1
left join atable a2 on a1.custid=a2.custid 
and datediff(day,a2.dt,a1.dt)<=30 and datediff(day,a2.dt,a1.dt)>0
group by a1.custid,a1.dt,a1.sales
order by 1,2
Run Code Online (Sandbox Code Playgroud)

Sample Demo in Postgres

为了更好的理解,看一下self-join使用的查询结果

select a1.*,a2.*
from atable a1
left join atable a2 on a1.custid=a2.custid 
and datediff(day,a1.dt,a2.dt)<=30 and datediff(day,a1.dt,a2.dt)>0
Run Code Online (Sandbox Code Playgroud)