sql - Formatting table with partitions -
what's best way of getting rows between occurrences opened , closed in postgresql?
+------------+----+------------+---------------------+ | event_id | id | occurrence | datetime | +------------+----+------------+---------------------+ | 1003603017 | | owner_from | 12/16/2016 4:44:16 | | 1003603017 | | owner_to | 12/16/2016 4:44:38 | | 1003603017 | | owner_from | 12/16/2016 4:44:38 | | 1003603017 | | opened | 12/16/2016 4:44:39 | | 1003603017 | b | owner_from | 12/16/2016 7:36:23 | | 1003603017 | | owner_to | 12/16/2016 7:36:23 | | 1003603017 | b | owner_to | 12/16/2016 9:00:01 | | 1003603017 | c | owner_from | 12/16/2016 9:00:01 | | 1003603017 | | closed | 12/16/2016 12:00:36 | | 1003603017 | d | owner_from | 12/17/2016 4:25:00 | | 1003603017 | c | owner_to | 12/17/2016 4:25:00 | | 1003603017 | d | owner_from | 12/17/2016 4:52:02 | | 1003603017 | d | owner_to | 12/17/2016 4:52:02 | | 1003603017 | d | opened | 12/17/2016 4:52:02 | | 1003603017 | d | owner_to | 12/17/2016 8:57:00 | | 1003603017 | e | owner_from | 12/17/2016 8:57:00 | | 1003603017 | d | closed | 12/17/2016 12:03:10 | +------------+----+------------+---------------------+
this easy ignore nulls
option on lag. here method uses cumulative maximum datetime
opened
, closed
:
select t.* (select t.*, max(case when occurrence = 'opened' datetime end) on (order datetime) mr_opened, max(case when occurrence = 'closed' datetime end) on (order datetime) mr_closed, t ) t mr_opened > mr_closed;
notes:
- this not include final
closed
. question not clear on requirement. - you might want partition
event_id
. question not clear on requirement. - in more recent versions of postgres, can use
filter
syntax instead ofcase
.
Comments
Post a Comment