Oracle
 SQL >> Database >  >> RDS >> Oracle

Numeri di versione a incremento automatico e date di validità in Oracle

Il tuo istinto di usare merge con row_number() è corretto, anche se il partition by è presumibilmente ridondante dato che stai già filtrando sulla città. L'ho esteso per gestire le date secondo due regole:

  • la primissima effective_dt_from e l'ultimissima effective_dt_to vengono lasciate invariate
  • tutto ciò che sta in mezzo incrementa giorno per giorno a partire da '2017-01-01'

Query:

merge into test t using ( select t.*, row_number() over(order by loc_sid asc) rn, count(*) over() cnt from test t where city = 'Chicago' ) t1 on (t1.loc_sid = t.loc_id) when matched the update set t.version = t1.rn, t.effective_dt_from = case when rn = 1 then t.effective_dt_from else date '2017-01-01' + rn - 2 end, t.effective_dt_to = case when rn = cnt then t.effective_dt_to else date '2017-01-01' + rn - 1 end

Il conteggio con finestra cnt è ciò che identifica la riga finale, così la sua data di fine può essere preservata, e l'offset rn - 2 fa sì che righe consecutive condividano una data di confine senza buchi.