我如何 window Postgre SQL 行基于行数据?
How do I window Postgre SQL rows based on row data?
我有一个 table,它有一个时间戳列和一些数据列。给定间隔长度 T(比如 30 分钟),我想将 table 划分为 'sessions'。如果时间戳值的差异小于 T,则两个相邻行(按时间戳排序时)在相同的 'session' 中。如果差异大于 T,则会话中断。例如,下面的 table 有两个大于 T 的间隔将会话分开。如何使用 SQL 生成会话列?
row | timestamp | session |
---|---|---|
1 | 18:00 | 1 |
2 | 18:02 | 1 |
3 | 18:04 | 1 |
4 | 18:30 | 1 |
5 | 19:10 | 2 |
6 | 19:20 | 2 |
7 | 20:20 | 3 |
您可以在时间戳上使用lag()
来衡量差异,然后使用累计和来计算会话:
select t.*,
sum(case when prev_timestamp > timetamp - interval '30 minute' then 0 else 1 end) over
(order by timestamp) as session
from (select t.*,
lag(timestamp) over (order by timestamp) as prev_timestamp
from t
) t;
或者,您可以在 Postgres 中将 count()
与 filter
一起使用:
select t.*,
1 + count(*) filter (where prev_timestamp < timestamp - interval '30 minute') over (order by timestamp) as session
from (select t.*,
lag(timestamp) over (order by timestamp) as prev_timestamp
from t
) t;