Pyt*_*00b 2 sql cumulative-sum amazon-redshift
我有一个事件表和一个票证(创建日期,person_id)表。当有人买票时,票表中会创建一行(Redshift)
我正在尝试制作快照表,以便我可以查看过去任何一天在该阶段购买了多少张门票。
到目前为止我有这个
select
trunc(e.created),
count(person_id) over (order by trunc(e.created) rows unbounded preceding) as cumulative_signups
from event e
LEFT JOIN person_tickets t on e.id = t.event_id
Run Code Online (Sandbox Code Playgroud)
问题是每次注册都会给我一行,这意味着我得到了这个,而不是每天一行。
trunc cumulative_signups
2016-01-15 1
2016-01-15 2
2016-01-15 3
2016-01-15 4
2016-01-16 5
trunc cumulative_signups
2016-01-15 4
2016-01-16 5
Run Code Online (Sandbox Code Playgroud)
您似乎想要的是使用窗口函数进行聚合:
select trunc(e.created), count(*) as day_count,
sum(count(*)) over (order by trunc(e.created) rows unbounded preceding) as cumulative_signups
from event e left join
person_tickets t
on e.id = t.event_id
group by trunc(e.created)
order by trunc(e.created);
Run Code Online (Sandbox Code Playgroud)
我认为rows unbounded preceding不需要sum(),但我还是把它留了下来(有一次,Redshift 需要带 的窗口子句order by)。