gpt4 book ai didi

sql - 在 Postgres 中查询连续列的 'run'

转载 作者:行者123 更新时间:2023-11-29 12:48:00 25 4
gpt4 key购买 nike

我有一张 table :

create table table1 (event_id integer, event_time timestamp without time zone);
insert into table1 (event_id, event_time) values
(1, '2011-01-01 00:00:00'),
(2, '2011-01-01 00:00:15'),
(3, '2011-01-01 00:00:29'),
(4, '2011-01-01 00:00:58'),
(5, '2011-01-02 06:03:00'),
(6, '2011-01-02 06:03:09'),
(7, '2011-01-05 11:01:31'),
(8, '2011-01-05 11:02:15'),
(9, '2011-01-06 09:34:19'),
(10, '2011-01-06 09:34:41'),
(11, '2011-01-06 09:35:06');

我想构造一个语句,给定一个事件可以返回从该事件开始的事件“运行”的长度。运行定义为:

  1. 如果两个事件的时间间隔在 30 秒以内,则它们将同时进行。
  2. 如果 A 和 B 一起跑,B 和 C 一起跑,那么 A 也在跑与 C.

但是我的查询不需要及时倒退,所以如果我选择事件 2,那么只有事件 2、3 和 4 应该算作以 2 开头的事件运行的一部分,而 3 应该是作为运行的长度返回。

有什么想法吗?我很难过。

最佳答案

这是递归 CTE 解决方案。 (孤岛和缺口问题自然适合递归 CTE)

WITH RECURSIVE runrun AS (
SELECT event_id, event_time
, event_time - ('30 sec'::interval) AS low_time
, event_time + ('30 sec'::interval) AS high_time
FROM table1
UNION
SELECT t1.event_id, t1.event_time
, LEAST ( rr.low_time, t1.event_time - ('30 sec'::interval) ) AS low_time
, GREATEST ( rr.high_time, t1.event_time + ('30 sec'::interval) ) AS high_time
FROM table1 t1
JOIN runrun rr ON t1.event_time >= rr.low_time
AND t1.event_time < rr.high_time
)
SELECT DISTINCT ON (event_id) *
FROM runrun rr
WHERE rr.event_time >= '2011-01-01 00:00:15'
AND rr.low_time <= '2011-01-01 00:00:15'
AND rr.high_time > '2011-01-01 00:00:15'
;

结果:

 event_id |     event_time      |      low_time       |      high_time      
----------+---------------------+---------------------+---------------------
2 | 2011-01-01 00:00:15 | 2010-12-31 23:59:45 | 2011-01-01 00:00:45
3 | 2011-01-01 00:00:29 | 2010-12-31 23:59:45 | 2011-01-01 00:01:28
4 | 2011-01-01 00:00:58 | 2010-12-31 23:59:30 | 2011-01-01 00:01:28
(3 rows)

关于sql - 在 Postgres 中查询连续列的 'run',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8246687/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com