Your ranges aren't
really continuous. For this to be the case, the previous end date would have to equal the current start date. Not have a gap of a day between them!
Anyway, as you're on 12c, you can do this easily with match_recognize. To do this you want to:
- Split the values up by title
- Sort the rows for each title by end date, then start date
The current row is then part of the previous range if its start date is less than or equal to the previous end date (plus one). i.e.:
rnge as datefrom <= prev(dateupto)+1
So you need to look for a pattern of any row, followed by zero or more rows matching the above condition.
To get the first and last values in the range, you need the min start and max end.
All together this gives you:
alter session set nls_date_format = 'dd Mon';
create table test_daterange (
title varchar2 ( 10 ) ,datefrom date ,dateupto date
) ;
insert into test_daterange values (
'Test A',to_date ( '01.12.2016' , 'DD.MM.YYYY' ) ,to_date ( '05.12.2016' , 'DD.MM.YYYY' )
) ;
insert into test_daterange values (
'Test A',to_date ( '02.12.2016' , 'DD.MM.YYYY' ) ,to_date ( '03.12.2016' , 'DD.MM.YYYY' )
) ;
insert into test_daterange values (
'Test A',to_date ( '06.12.2016' , 'DD.MM.YYYY' ) ,to_date ( '07.12.2016' , 'DD.MM.YYYY' )
) ;
insert into test_daterange values (
'Test A',to_date ( '08.12.2016' , 'DD.MM.YYYY' ) ,to_date ( '09.12.2016' , 'DD.MM.YYYY' )
) ;
insert into test_daterange values (
'Test B',to_date ( '10.12.2016' , 'DD.MM.YYYY' ) ,to_date ( '11.12.2016' , 'DD.MM.YYYY' )
) ;
insert into test_daterange values (
'Test A',to_date ( '13.12.2016' , 'DD.MM.YYYY' ) ,to_date ( '16.12.2016' , 'DD.MM.YYYY' )
) ;
select * from test_daterange
match_recognize (
partition by title
order by dateupto, datefrom
measures
min (DATEFROM) as st_dt,
max (dateupto) as en_dt
one row per match
pattern (st rnge*)
define
rnge as datefrom <= prev(dateupto)+1
)
order by st_dt;
TITLE ST_DT EN_DT
Test A 01 Dec 09 Dec
Test B 10 Dec 11 Dec
Test A 13 Dec 16 Dec
If you want to know more about working with date ranges, I recommend reading Stew Ashton's blog posts on this:
https://stewashton.wordpress.com/category/date-ranges/