SimonSellick
Programmer
Hi,
I've been worrying at this one for a while without result. The person responsible for making it work resorted to a cursor but I feel that it should be possible to develop a set-based query.
In essence: there are records recording periods worked, each with a start and end date. There may be overlaps and gaps. I need a list of continuous periods defined as the earliest start date to the latest end date where no gap of 1 or more days exists. Note that a pair of records such that the start date of one immediately follows the end date of the other counts as continuous.
Here is some sample data:
And this is what I would expect as the result:
I have added id, scenario and period to show where the data came from; they aren't necessary in either input or output.
I have tried the things that seemed obvious, but unsuccessfully. Any suggestions appreciated. I am using SQL Server 2008 R2.
I've been worrying at this one for a while without result. The person responsible for making it work resorted to a cursor but I feel that it should be possible to develop a set-based query.
In essence: there are records recording periods worked, each with a start and end date. There may be overlaps and gaps. I need a list of continuous periods defined as the earliest start date to the latest end date where no gap of 1 or more days exists. Note that a pair of records such that the start date of one immediately follows the end date of the other counts as continuous.
Here is some sample data:
Code:
id scenario from_date to_date
1 S01 2001-01-01 2001-01-31
2 S01 2001-02-01 2001-02-28
3 S01 2001-01-10 2001-02-09
4 S01 2001-01-20 2001-01-31
5 S01 2001-02-10 2001-02-19
6 S02 2001-04-01 2001-04-30
7 S02 2001-05-01 2001-05-31
8 S03 2001-07-01 2001-07-31
9 S04 2001-09-01 2001-09-19
10 S04 2001-09-10 2001-09-30
Code:
period start_date end_date
S01 01-Jan-2001 28-Feb-2001
S02 01-Apr-2001 31-May-2001
S03 01-Jul-2001 31-Jul-2001
S04 01-Sep-2001 30-Sep-2001
I have tried the things that seemed obvious, but unsuccessfully. Any suggestions appreciated. I am using SQL Server 2008 R2.