首页 > 解决方案 > 选择最近的非空行

问题描述

我在 Postgres 中有一个带有时间戳的表和 6 列(A、B、C、D、E、F)的值。每 10 分钟将新记录附加到此表中,但是对于 B、D、F 列,实际值仅每 30 分钟获取一次,这意味着只有每 3 行不为空。

我想编写一个查询,每列输出最近的记录。我唯一想到的是写两个查询:

SELECT  A,C,E
    FROM data_prices 
    ORDER BY date_of_record DESC LIMIT 1



SELECT  B,D,F
        FROM data_prices 
        WHERE B is not null, D is not null, F is not null
        ORDER BY date_of_record DESC LIMIT 1

然后将结果加入 1 个 6 列 1 行的表中。但是我不知道该怎么做,因为在文档中我发现了诸如UNION, INTERSECT, EXCEPT附加数据之类的操作,而不是创建一个更宽的表。任何想法如何将这 2 个选择加入 1 个 6 列的表?或者也许更聪明的方法来获取表中每列的最新非 NULL 结果?

标签: sqlpostgresql

解决方案


不幸的是,Postgres 不支持lag(ignore nulls).

一种方法使用first_value()

select date_of_record, a,
       first_value(b) over (order by (b is not null) desc, date_of_record desc) as last_b,
       c,
       first_value(d) over (order by (d is not null) desc, date_of_record desc) as last_d,
       e,
       first_value(f) over (order by (f is not null) desc, date_of_record desc) as last_f
from t
order by date_of_record desc
limit 1;

推荐阅读