Skip to content

Instantly share code, notes, and snippets.

@randyzwitch
Created January 8, 2015 15:48
Show Gist options
  • Save randyzwitch/d0d0ec0310e10657a469 to your computer and use it in GitHub Desktop.
Save randyzwitch/d0d0ec0310e10657a469 to your computer and use it in GitHub Desktop.
Postgres Lag Window Function
--Create boundaries at 30 minute timeout
select
uid,
event_timestamp,
(extract(epoch from event_timestamp) - lag(extract(epoch from event_timestamp)) OVER (PARTITION BY uid ORDER BY event_timestamp))/60 as minutes_since_last_interval,
case when extract(epoch from event_timestamp) - lag(extract(epoch from event_timestamp)) OVER (PARTITION BY uid ORDER BY event_timestamp) > 30 * 60 then 1 ELSE 0 END as new_event_boundary
from single_col_timestamp;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment