I have a table like this:
Date | Group name | value |
---|---|---|
2022-01-01 | A | 1.0 |
2022-01-15 | A | 0.5 |
2022-01-31 | A | 0.2 |
but this contains only 3 days. I need a table with full-calendar dates, a row for every day of the year where the value is the last available.
For example, all records from 1 Jan 2022 to 14 Jan have value 1.0 (scoped to group_name
'A').
I have tried using LAST_VALUE()
but it's not working.
WITH dates AS (
SELECT
date::date
FROM generate_series ( '2022-01-01'::timestamp, '2022-01-31'::timestamp, '1 day'::interval) date
), incomplete_table AS (
SELECT * FROM (VALUES
('2022-01-01'::date, 'a', 1),
('2022-01-15'::date, 'a', 0.5),
('2022-01-31'::date, 'a', 0.2),
('2022-01-02'::date, 'b', 0.1),
('2022-01-10'::date, 'b', 0.15),
('2022-01-20'::date, 'b', 0.15)
) AS t (date,group_name, value)
)
SELECT
dates.date,
group_name,
value,
LAST_VALUE(value) OVER (ORDER BY dates.date DESC) as last_value_window
FROM dates
LEFT JOIN incomplete_table ON incomplete_table.date = dates.date
ORDER BY dates.date DESC;
scoped to group_name A
means you want one row per day and group name? Or fill indate
andgroup_name
from the last nonnull value? Independently? Also, please always declare your version of Postgres. Also, an exact table definition (CREATE TABLE
statement) is much better than a CTE, telling us exact data types and constraints.