Re: Window function for get the last value to extend missing rows

From: Kirk Wolak <wolakk(at)gmail(dot)com>
To: Andrew Gierth <andrew(at)tao11(dot)riddles(dot)org(dot)uk>
Cc: Durumdara <durumdara(at)gmail(dot)com>, Postgres General <pgsql-general(at)postgresql(dot)org>
Subject: Re: Window function for get the last value to extend missing rows
Date: 2023-05-13 08:58:26
Message-ID: CACLU5mTVY46hcK4F-HfrDgff98G=wNmOj94bLYkxOqDz3Ktbdg@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Sat, May 13, 2023 at 2:18 AM Andrew Gierth <andrew(at)tao11(dot)riddles(dot)org(dot)uk>
wrote:

> >>>>> "Durumdara" == Durumdara <durumdara(at)gmail(dot)com> writes:
>
> create table tmp_test_table(mmin,val)
> as select o, v
> from unnest(array[1,5,NULL,3,NULL,NULL,10,7,NULL,NULL,NULL,4])
> with ordinality as u(v,o);
> select * from tmp_test_table order by mmin;
>

That seems like a lot of work.
If you have ALL the values (no missing values) a simple CTE handles this:

https://www.db-fiddle.com/f/wKyQV1imGsewR9Az7hi193/0

WITH RECURSIVE rec_cte(mmin, value) AS (
SELECT mmin, value from tmp_test_table where mmin=1
UNION ALL
SELECT t.mmin, COALESCE(t.value,r.value)
FROM tmp_test_table t, rec_cte r WHERE r.mmin=(t.mmin-1)
)
SELECT * from rec_cte order by mmin;

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Adrian Klaver 2023-05-13 14:59:35 Re: PG_Cron - Error Message Connection failed
Previous Message Kirk Wolak 2023-05-13 07:59:35 Re: Adding SHOW CREATE TABLE