【问题标题】:Query - find empty interval in series of timestamps查询 - 在一系列时间戳中查找空区间
【发布时间】:2013-12-13 05:09:29
【问题描述】:

我有一个存储历史数据的表。我每 30 秒从不同类型的源中插入一行,显然有一个相关的时间戳。

让我们将我的参数设置为 1 小时。

由于我是按时间收取服务费用的,因此我需要知道,例如,在特定月份中,该月内是否有一个时间间隔等于或超过我的 1 小时间隔。

表格的简化结构如下:

tid serial primary key,
tunitd id int,
tts timestamp default now(),
tdescr text

我不想编写一个函数来循环遍历所有记录,逐一比较它们,因为我认为这会耗费时间和内存。

有没有办法直接从 SQL 中执行此操作,可能使用 PostgreSQL 中的间隔类型?

谢谢。

【问题讨论】:

  • 是的,可以使用 SQL。到目前为止,您尝试过什么?

标签: sql postgresql intervals


【解决方案1】:

这个小 SQL 查询将显示持续时间超过一小时的所有间隙:

select tts, next_tts, next_tts-tts as diff from
(select a.tts, min(b.tts) as next_tts
from test1 a
inner join test1 b ON a.tts < b.tts
GROUP BY a.tts) as c
where next_tts - tts > INTERVAL '1 hour'
order by tts;

SQL Fiddle

【讨论】:

    猜你喜欢
    • 2023-01-12
    • 2017-04-30
    • 2017-08-15
    • 2015-02-09
    • 1970-01-01
    • 1970-01-01
    • 2017-09-07
    • 2023-03-23
    • 2015-12-09
    相关资源
    最近更新 更多