Merge overlapping time-periods

From: "Jira, Marcel" <Marcel(dot)Jira(at)wu(dot)ac(dot)at>
To: "'pgsql-sql(at)postgresql(dot)org'" <pgsql-sql(at)postgresql(dot)org>
Subject: Merge overlapping time-periods
Date: 2011-06-15 15:23:15
Message-ID: D793F5C522F1DD40BB9DC43586C57637DE06389FE8@MBX-B.ad.wu-wien.ac.at
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Hi!

Although I try for some time, I am not able to write an SQL-Query that can do the following:

I have a very big table (let's call it "mytable") with information like this:

ID BEG END
1 2000-01-01 2000-03-31
1 2000-04-01 2000-05-31
1 2000-04-15 2000-07-31
1 2000-09-01 2000-10-31
2 2000-02-01 2000-03-15
2 2000-01-15 2000-03-31
2 2000-04-01 2000-04-15
3 2000-06-01 2000-06-15
3 2000-07-01 2000-07-15

There's an ID and time periods defined by a start value (BEG) and an end value (END)

I want to merge all periods belonging to the same ID, iff their time periods are overlapping or in a direct sequence.

Therefore the result should somehow look like this:

ID BEG END

1 2000-01-01 2000-07-31

1 2000-09-01 2000-10-31

2 2000-01-15 2000-03-31

2 2000-04-01 2000-04-15

3 2000-06-01 2000-06-15

3 2000-07-01 2000-07-15

I tried using "WITH RECURSIVE" but I didn't succeed.

My server is PostgreSQL 8.4. Unfortunately I can't do anything like update or install some fancy module...

Thank you for your help!

Best regards,

Marcel Jira

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Charles N. Charotti 2011-06-15 15:40:48 Calling inner functions vs. Begin-End blocs
Previous Message greg.fenton 2011-06-15 01:01:51 Re: Select For Update and Left Outer Join