我们有几个独立事件表。 对于给定的 id,我们想知道 2 个事件之间的时间差。 现在,对于给定的 id,可以有多个相同的事件,我们只对“下一个”事件感兴趣。
例子:
http://sqlfiddle.com/#!4/1f724/6/0
架构
create table event_a (
timestmp timestamp(3),
id varchar2(50)
);
create table event_b (
timestmp timestamp(3),
id varchar2(50)
);
insert into event_a values (to_timestamp('2015-05-12 10:22:00', 'YYYY-MM-DD HH24:MI:SS'), 'x');
insert into event_b values (to_timestamp('2015-05-12 10:22:05', 'YYYY-MM-DD HH24:MI:SS'), 'x');
insert into event_a values (to_timestamp('2015-05-12 10:22:08', 'YYYY-MM-DD HH24:MI:SS'), 'x');
insert into event_b values (to_timestamp('2015-05-12 10:22:10', 'YYYY-MM-DD HH24:MI:SS'), 'x');
查询
这是我想出的查询,但在我看来有点太复杂了。我想知道是否有更好的方法来做到这一点。
如果这些表中有大量数据,此查询也需要很长时间才能运行。
select a.id, nvl((extract(day from (b.timestmp - a.timestmp)) * 86400
+ extract(hour from (b.timestmp - a.timestmp)) * 3600
+ extract(minute from (b.timestmp - a.timestmp)) * 60
+ extract(second from (b.timestmp - a.timestmp)) ), 0) as duration_in_sec
from event_a a
join event_b b on a.id = b.id and b.timestmp = (
select min(timestmp)
from event_b
where id = a.id
and timestmp >= a.timestmp
)
最佳答案
这个解决方案应该更快,因为它没有自连接子查询:
select id, extract(day from (d)) * 86400 + extract(hour from (d)) * 3600
+ extract(minute from (d)) * 60 + extract(second from (d)) duration
from (
select a.id, b.timestmp - a.timestmp d,
row_number() over (partition by a.id, a.timestmp order by b.timestmp) rn
from event_a a
join event_b b on a.id = b.id and a.timestmp <= b.timestmp
order by a.timestmp)
where rn = 1
关于sql - 连接2个表计算时间差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30185741/