您可以在日期差异声明中将表连接到自身上。实际上,这是 postgres,一个简单的减号就可以了。
该子查询将查找所有属于“开始事件”的记录。也就是说,在它之前的 30 秒内没有发生其他事件记录的所有事件记录:
(Select a.event_id, a.event_time from
(Select event_id, event_time from table1) a
left join
(select event_id, event_time from table1) b
on a.event_time - b.event_time < '00:00:30' and a.event_time - b.event_time > '00:00:00'
where b.event_time is null) startevent
进行一些更改...相同的逻辑,除了选择“结束”事件:
(Select a.event_id, a.event_time from
(Select event_id, event_time from table1) a
left join
(select event_id, event_time from table1) b
on b.event_time - a.event_time < '00:00:30' and b.event_time - a.event_time > '00:00:00'
where b.event_time is null) end_event
现在我们可以将它们连接在一起以关联哪个开始事件到哪个结束事件:
(仍在写...有几种方法可以解决这个问题。我假设只有示例具有线性 ID 号,因此您需要将开始事件时间加入到结束事件时间中,在活动时间)。
这是我的最终结果......有点嵌套了很多子选择
select a.start_id, case when a.event_id is null then t1.event_id::varchar else 'single event' end as end_id
from
(select start_event.event_id as start_id, start_event.event_time as start_time, last_event.event_id, min(end_event.event_time - start_event.event_time) as min_interval
from
(Select a.event_id, a.event_time from
(Select event_id, event_time from table1) a
left join
(select event_id, event_time from table1) b
on a.event_time - b.event_time < '00:00:30' and a.event_time - b.event_time > '00:00:00'
where b.event_time is null) start_event
inner join
(Select a.event_id, a.event_time from
(Select event_id, event_time from table1) a
left join
(select event_id, event_time from table1) b
on b.event_time - a.event_time < '00:00:30' and b.event_time - a.event_time > '00:00:00'
where b.event_time is null) end_event
on end_event.event_time > start_event.event_time
--check for only event
left join
(Select a.event_id, a.event_time from
(Select event_id, event_time from table1) a
left join
(select event_id, event_time from table1) b
on b.event_time - a.event_time < '00:00:30' and b.event_time - a.event_time > '00:00:00'
where b.event_time is null) last_event
on start_event.event_id = last_event.event_id
group by 1,2,3) a
left join table1 t1 on t1.event_time = a.start_time + a.min_interval
结果为 start_id、end_Id:
1;"4"
5;"6"
7;"单个事件"
8;"单个事件"
9;"11"
我不得不使用第三个左连接来挑选单个事件作为检测既是开始事件又是结束事件的事件的方法。最终结果在 ID 中,如果您需要与 ID 不同的信息,可以将其链接回原始表格。如果您有数百万个事件,不确定此解决方案将如何扩展……可能是个问题。