【问题标题】:Select most recent non null row选择最近的非空行
【发布时间】:2021-08-13 18:52:42
【问题描述】:

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

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

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 结果?

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    很遗憾,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;
    

    【讨论】:

      猜你喜欢
      • 2019-03-29
      • 2016-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多