sql - Group By with Window Function instead of two Window Functions -
i have table 2 columns: time
, id
. think of rows sorted first id, time.
╔════════╦══════════╗ ║ time ║ id ║ ╠════════╬══════════╣ ║ 9:10 ║ 1 ║ ║ 9:20 ║ 1 ║ ║ 10:10 ║ 1 ║ ║ 11:30 ║ 1 ║ ║ 11:50 ║ 1 ║ ║ 10:20 ║ 2 ║ ║ 10:30 ║ 2 ║ ║ 11:20 ║ 3 ║ ║ 11:50 ║ 3 ║ ╚════════╩══════════╝
i want select rows id
same 'previous' row id
, time difference previous row less hour.
this can done first creating table there 3rd column of time differences previous row , 4th column of id differences, , selecting rows id_diff 0 , time_diff above 1 hour.
but method seems inelegant because want @ each id
separately , inside each id
@ times , check if consecutive difference above hour. that'll reflect better logic of looking @ each id separately, because different entities.
so how can done grouping on id, instead of using window functions twice? i'm aware of group by
's existence.
the code works, 2 window functions:
select auxiliary_table_with_lag_diffs.* ( select info.*, time-lag(time) on (order id, time ) diff_time, id-lag(id) on (order id, time) diff_id info )auxiliary_table_with_lag_diffs diff_time>'01:00:00' , diff_id=0 order id, time;
you need one analytic function call here: previous time within same id.
select * ( select info.*, time - lag(time) on (partition id order time) diff_time info ) auxiliary_table_with_lag_diffs diff_time > interval '1 hour'; order id, time;
Comments
Post a Comment