Skip to content

Instantly share code, notes, and snippets.

@sjtalkar
Last active October 25, 2020 00:30
Show Gist options
  • Save sjtalkar/bd50792681ebd73625328683f06fa132 to your computer and use it in GitHub Desktop.
Save sjtalkar/bd50792681ebd73625328683f06fa132 to your computer and use it in GitHub Desktop.
Using LEAD window function in an update and merge
--Oracle Merge
merge into depreciation_rate d
using
(select asset,
country,
effective_from,
lead(effective_from) over (partition by asset, country order by effective_from) - 1/86400 as effective_until
from depreciation_rate) n
on (d.asset = n.asset
and d.country = n.country
and d.effective_from = n.effective_from)
when matched then
update set d.effective_from = n.effective_from;
--PostgreSQL update
update depreciation_rate d
set effective_until = (select
effective_until
from (select lead(effective_from) over (partition by asset, country order by effective_from) as effective_until,
ROWID as rid
from depreciation_rate) a
where a.rid = d.ROWID);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment