Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Group multiple events for ID in postgreSQL data

I’m trying to select pairs of events from my data. I have a data that looks like this:

create table test(id,status,created)as values
 (1, 'on','2024-09-01'::date)
,(2, 'on','2024-09-02'::date)
,(1,'off','2024-09-03'::date)
,(1, 'on','2024-09-04'::date)
,(2,'off','2024-09-05'::date)
,(3, 'on','2024-09-06'::date)
,(1,'off','2024-09-07'::date)
,(4,'off','2024-09-08'::date);

I would like to have data like this:

id switched_on switched_off
1 2024-09-01 2024-09-03
1 2024-09-04 2024-09-07
2 2024-09-02 2024-09-05
3 2024-09-06
4 2024-09-08

I am interested in:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  1. multiple events for the same id in the data
  2. null values when either end of event pair is missing

>Solution :

An example using the self-join:

  1. Match on id
  2. Make sure the left table is for earlier on events, right for later off.
  3. This matches every on event with all later offs for each id. A distinct on keeps only a single match for each id and on event, selecting the soonest off.

demo at db<>fiddle

select distinct on (1,2)
       coalesce(t1.id,t2.id)
      ,t1.created as switched_on 
      ,t2.created as switched_off
from test as t1 
full join test as t2 
       on t1.id=t2.id 
      and t1.created<t2.created
where coalesce(t1.status,'on')='on' 
  and coalesce(t2.status,'off')='off'
order by 1,2, t2.created-t1.created;
coalesce switched_on switched_off
1 2024-09-01 2024-09-03
1 2024-09-04 2024-09-07
2 2024-09-02 2024-09-05
3 2024-09-06 null
4 null 2024-09-08
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading