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

ORACLE SQL:crea una nuova riga in base all'intervallo di date

Puoi utilizzare una query ricorsiva (che funzionerà indipendentemente da quanti mesi coprono gli intervalli):

WITH months ( id, start_date, end_date, final_date ) AS (
  SELECT id,
         start_date,
         LEAST( LAST_DAY( start_date ), end_date ),
         end_date
  FROM   table_name
UNION ALL
  SELECT id,
         end_date + INTERVAL '1' DAY,
         LEAST( ADD_MONTHS( end_date, 1 ), final_date ),
         final_date
  FROM   months
  WHERE  end_date < final_date
)
SEARCH DEPTH FIRST BY final_date SET dt_order
SELECT id,
       start_date,
       end_date
FROM   months;

Quale, per i dati di esempio:

CREATE TABLE table_name (id, start_date, end_date) AS
SELECT 44, DATE '2020-01-04', DATE '2020-01-04' FROM DUAL UNION ALL
SELECT 44, DATE '2020-01-30', DATE '2020-02-10' FROM DUAL UNION ALL
SELECT 44, DATE '2020-02-27', DATE '2020-03-03' FROM DUAL;

Uscite:

db<>violino qui