sql >> Base de Datos >  >> RDS >> Oracle

Cómo crear GROUP BY en la fecha mínima y máxima

Este es un tipo de problema de lagunas e islas con cadenas de datos. Sugeriría usar una left join para encontrar dónde comienzan las islas. Luego una suma acumulativa y agregación:

select emp_id, title, min(start_date), max(end_date)
from (select t.*,
             sum(case when tprev.emp_id is null then 1 else 0 end) over
                 (partition by t.emp_id, t.title order by t.start_date) as grouping
      from t left join
           t tprev
           on t.emp_id = tprev.emp_id and
              t.title = tprev.title and
              t.start_date = tprev.end_date + 1
     ) t
group by grouping, emp_id, title;