Oracle
 sql >> Database >  >> RDS >> Oracle

Sql:unione di righe se la data si connette

Puoi usare una tale logica con sum aggregato e lag funzioni della finestra come di seguito:

select clientid, min(startdate) as startdate, max(enddate) as enddate
  from
(
select tt.*, sum(grp) over (order by clientid, startdate) sm 
  from
(
  with t(clientid, startdate, enddate) as
  (
   select 1, date'2017-10-10', date'2017-10-12' from dual union all
   select 1, date'2017-10-12', date'2017-10-13' from dual union all
   select 1, date'2017-10-13', date'2017-10-17' from dual union all  
   select 1, date'2017-11-10', date'2017-11-17' from dual union all  
   select 1, date'2017-11-17', date'2017-11-23' from dual union all  
   select 1, date'2017-12-12', date'2017-12-14' from dual union all
   select 2, date'2017-11-10', date'2017-11-15' from dual union all  
   select 2, date'2017-12-01', date'2017-12-02' from dual union all  
   select 2, date'2017-12-02', date'2017-12-05' from dual
  )
 select clientid, 
        decode(nvl(lag(enddate) over 
                   (order by enddate),startdate),startdate,0,1) 
                   as grp, --> means prev. value equals or not 
        row_number() over (order by clientid, enddate) as rn, startdate, enddate
    from t
) tt
order by rn
) 
group by clientid, sm 
order by clientid, enddate;

CLIENTID    STARTDATE   ENDDATE
----------  ----------  ----------
1           10.10.2017  17.10.2017
1           10.11.2017  23.11.2017
1           12.12.2017  14.12.2017
2           10.11.2017  15.11.2017
2           01.12.2017  05.12.2017

Dimostrazione Rextester

Esecuzione passo passo della query per una migliore comprensione