PostgreSQL:使用组中的前一个NOT NULL值向前填充NULL值

pvcm50d1  于 2023-02-22  发布在  PostgreSQL
关注(0)|答案(1)|浏览(206)

我正在尝试填充NULL值在多个列(不同的列类型INT,VARCHAR)与以前的NOT NULL值在一组按日期排序。考虑下表:

我想到达这里:

CREATE TABLE IF NOT EXISTS test (
   id VARCHAR,
   date DATE,
   value_1 INT,
   value_2 VARCHAR
);

INSERT INTO test VALUES 
(1, '2022-01-01', 5, 'asdf'),
(1, '2022-01-02', NULL, NULL),
(1, '2022-01-03', NULL, 'def'),
(1, '2022-01-04', 4, NULL),
(2, '2022-01-01', 1, 'a'),
(2, '2022-01-02', NULL, NULL),
(2, '2022-01-03', 2, 'b'),
(2, '2022-01-04', NULL, NULL);
wfveoks0

wfveoks01#

有一天,PostgreSQL可能会支持LEADLAG函数的IGNORE NULLS选项。
同时,必须使用窗口函数来建立组,然后选择每个组中的最大值。

SELECT id, date,
       MAX(value_1) OVER (PARTITION BY id, grp_1) AS value_1,
       MAX(value_2) OVER (PARTITION BY id, grp_2) AS value_2
FROM(
    SELECT *,
          COUNT(value_1) OVER (PARTITION BY id ORDER BY Date DESC) as grp_1,
          COUNT(value_2) OVER (PARTITION BY id ORDER BY Date DESC) as grp_2
    FROM test
) T
ORDER BY ID, date

相关问题