【问题标题】:how can I get the last value for each key in a set of postgres hstore records?如何获取一组 postgres hstore 记录中每个键的最后一个值?
【发布时间】:2021-04-14 13:58:47
【问题描述】:

我有一个传感器读数表作为 postgres hstore key-value pairs。 每条记录都有一个以 1 秒为间隔的时间戳。 并非所有传感器都每秒记录一次。

表格本质上是:

create table readings (
    timer timestamp primary key,
    readings hstore
);

hstore 包含 ( ) 键/值对,用于在时间戳中指定的时间获取读数。

例如:“67”“-45.67436”、“68”“176.5424”可以是表示纬度和经度的键/值对,在计时器列中带有时间戳。

在给定的一分钟内会有几个纬度/经度 hstore 对,我想要的查询将返回该分钟时间序列中的最后一个(对于每个键)。

我想每隔 1 分钟检索一次 hstore 中每个传感器的最新值。

基本上: 获取那一分钟的时间戳和 hstore 集。 从该集合中获取密钥。 从集合中具有最新时间戳的键值对中获取该键的值 返回 1 分钟时间戳和生成的 hstore 下一分钟重复

如果这是最好的方法,我对 pl/pgsql 函数很满意。

【问题讨论】:

  • 欢迎来到 SO 社区。请花几分钟时间来获取Tour 并查看帮助部分How to Ask。特别是发布您的表格定义 (ddl) 和示例日期,作为文本 - 无图像,以及该数据的预期结果。另外显示您尝试过的查询并具体说明您遇到的问题。

标签: postgresql hstore windowing


【解决方案1】:

“我想要的查询将返回时间序列中的最后一个 分钟(每个键)”

你可以使用 windows 功能,我猜你有不同的传感器

select * from 
( 
   select * , row_number() over (partition by sensorid, to_char(timer, 'YYYY-MM-DD HH:MM') order by timer desc) rn
) t
where rn = 1

【讨论】:

    【解决方案2】:
    with t(t, h) as (values
        ('2000-01-01 01:01:01'::timestamp, 'a=>1,b=>2'::hstore),
        ('2000-01-01 01:01:02', 'a=>3'),
        ('2000-01-01 01:02:03', 'b=>4'),
        ('2000-01-01 01:02:05', 'a=>2,b=>3'))
    select
        date_trunc('minute', t),
        jsonb_object_agg(k, v order by t)
    from t, each(h) as h(k,v)
    group by date_trunc('minute', t);
    
    ┌─────────────────────┬──────────────────────┐
    │     date_trunc      │   jsonb_object_agg   │
    ├─────────────────────┼──────────────────────┤
    │ 2000-01-01 01:01:00 │ {"a": "3", "b": "2"} │
    │ 2000-01-01 01:02:00 │ {"a": "2", "b": "3"} │
    └─────────────────────┴──────────────────────┘
    

    demo

    【讨论】:

      猜你喜欢
      • 2023-01-28
      • 2017-02-19
      • 1970-01-01
      • 2020-10-01
      • 2022-09-23
      • 1970-01-01
      • 2017-12-15
      • 2022-01-19
      • 1970-01-01
      相关资源
      最近更新 更多