I have a table “orders” in postgres with columns “offer_id” and “date”. I need to write a code which must fill in all empty cases in column “offer_id”, using the previous results. I try to use “lag” function but the problem is that it only manages with one single NULL but not several. How to fix that?
image here
I tried this
with orders as (
select 2 as offer_id, '2021-01-01'::date as date union all
select 3 as offer_id, '2021-01-02'::date as date union all
select null as offer_id, '2021-01-03'::date as date union all
select null as offer_id, '2021-01-04'::date as date union all
select null as offer_id, '2021-01-05'::date as date union all
select 4 as offer_id, '2021-01-07'::date as date union all
select 5 as offer_id, '2021-01-08'::date as date union all
select null as offer_id, '2021-01-09'::date as date union all
select 8 as offer_id, '2021-01-10'::date as date union all
select 9 as offer_id, '2021-01-11'::date as date union all
select null as offer_id, '2021-01-12'::date as date union all
select null as offer_id, '2021-01-13'::date as date union all
select 13 as offer_id, '2021-01-14'::date as date union all
select 13 as offer_id, '2021-01-15'::date as date union all
select null as offer_id, '2021-01-16'::date as date
)
select *, CASE WHEN offer_id IS NULL
THEN LAG(offer_id) OVER (ORDER BY date) ELSE offer_id END updated_offer_id
from orders
New contributor
Bolbi Stroganovsky is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.