Esto parece un poco complicado, por lo que estaría interesado en mejoras.
select distinct emp_id,
nvl(x_start_date,
lag(x_start_date)
over (partition by emp_id
order by rn)) as start_date,
nvl(x_end_date,
lead(x_end_date)
over (partition by emp_id
order by rn nulls first))
as end_date,
rating,
department
from (
select emp_id, start_date, end_date, rating, department,
case start_date
when lag(end_date)
over (partition by emp_id, rating, department
order by start_date) then null
else start_date end as x_start_date,
case end_date
when lead(start_date)
over (partition by emp_id, rating, department
order by start_date) then null
else end_date end as x_end_date,
rownum as rn
from table1
)
where x_start_date is not null or x_end_date is not null
order by emp_id, start_date
/
Con estos datos de prueba:
EMP_ID START_DA END_DATE RA DEPARTMENT SALARY
---------- -------- -------- -- -------------------- ----------
2000 01012010 01012011 A HR 9000
2000 01012011 01012012 A HR 10000
2000 01012012 01012013 A+ HR 20000
2000 01012013 01012014 A HR 20000
2000 01012014 12319999 A HR 21000
3000 01012011 01012012 B Operations 50000
3000 01012012 12319999 B Operations 60000
4000 07012011 07012012 B Operations 50000
4000 07012012 07012013 B Operations 50000
4000 07012013 12319999 B Operations 60000
Me sale esto:
EMP_ID START_DA END_DATE RA DEPARTMENT
---------- -------- -------- -- --------------------
2000 01012010 01012012 A HR
2000 01012012 01012013 A+ HR
2000 01012013 12319999 A HR
3000 01012011 12319999 B Operations
4000 07012011 12319999 B Operations
También probé con un emp_id
(4000
) que tenía tres intervalos de fechas contiguos y se ocupaba de ese OK:el where
externo cláusula hace que las entradas intermedias desaparezcan, esencialmente. Editado para agregar :ahora también funciona con intervalos de fechas adicionales para 2000/A
, ya que arreglé el orden en el lead
externo /lag
particiones.
La consulta interna borra todo menos la primera fecha de inicio y la última fecha de finalización para un bloque contiguo, y la consulta externa usa una segunda ronda de lead
y lag
para fusionarlos en filas idénticas, que el distinct
luego colapsa.
Estoy asumiendo start_date
y end_date
son DATE
campos, no VARCHAR2
y tiene NLS_DATE_FORMAT
establecido en MMDDYYYY
. Si se almacenan como cadenas, lo cual es una mala idea, necesita to_date()
en bastantes lugares para que el pedido funcione correctamente.