【问题标题】:How to match Values based on time stamps and when time stamp does not exist the value is the previous time stamp's value如何根据时间戳匹配值,当时间戳不存在时,该值是前一个时间戳的值
【发布时间】:2019-12-12 16:22:13
【问题描述】:

我正在尝试生成一个报告,该报告将根据创建的时间序列加入一个表,该时间序列以 1 分钟为间隔,每天总共 1440 行。

我想将每个间隔与另一个表上的时间戳连接起来,但当该时间戳在表中不存在时,该值来自上一个时间戳

Generated_TIME_STAMP | TIMESTAMP             | VALUE
12/01/2019 00:01:000 | 12/01/2019 00:01:000  | 1
12/01/2019 00:02:000 | NULL                  | 1
12/01/2019 00:03:000 | 12/01/2019 00:03:000  | 3
12/01/2019 00:04:000 | 12/01/2019 00:04:000  | 7
12/01/2019 00:03:000 | NULL                  | 7

因此,生成一个时间序列,将该时间序列与表的时间戳连接以识别这些时间戳的值,当表中不存在时间戳时,值列会从确实存在的上一个时间戳中获取值.

【问题讨论】:

  • 您当前的查询是什么?

标签: sql postgresql timestamp


【解决方案1】:

您可以使用generate_series() 生成行。然后,您可以使用横向 join 获取该行:

select ts.ts,
       (case when t.timestamp = ts.ts then t.timestamp end) as timestamp,
       t.value
from generate_series('2019-12-01'::timestamp, '2019-12-01 23:59:00'::timestamp, interval '1 minute') ts(ts) left join lateral
     (select t.*
      from yourtable t
      where t.timestamp <= ts.ts
      order by t.timestamp desc
      limit 1
     ) t;

【讨论】:

    猜你喜欢
    • 2019-12-31
    • 2015-11-29
    • 2013-11-27
    • 2016-01-17
    • 1970-01-01
    • 2020-02-09
    • 2021-01-02
    • 2023-02-08
    • 1970-01-01
    相关资源
    最近更新 更多