Skip to content

Instantly share code, notes, and snippets.

@stefanoc
Last active June 21, 2016 11:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stefanoc/cd0514c1f250c2ddbff025633d180bd0 to your computer and use it in GitHub Desktop.
Save stefanoc/cd0514c1f250c2ddbff025633d180bd0 to your computer and use it in GitHub Desktop.
Window function example
truncate table events;
CREATE TABLE events(ref_id integer, event_type text, ts integer);
INSERT INTO events (ref_id, event_type, ts) VALUES (1, 'foo', 1), (1, 'bar', 1), (2, 'foo', 0), (3, 'foo', 0), (1, 'foo', 4), (3, 'foo', 7), (2, 'bar', 10);
select
ref_id,
event_type,
ts,
first_value(ts) over (
partition by ref_id, event_type order by ts asc rows between 1 following and unbounded following
) - ts as delta
from events
where event_type = 'foo'
order by ts
2 foo 0
3 foo 0 7
1 foo 1 3
1 foo 4
3 foo 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment