We have a couple of seperate event tables. For a given id we would like to know the time difference between 2 events. Now, there can be several of the same events for a given id, we are only interested in the "next" event.
Example:
http://sqlfiddle.com/#!4/1f724/6/0
Schema
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');
Query
This is the query I came up with, but it seems to me to be a little too complex. I was wondering if there is a better way to do this.
This query also takes a long time to run if there is a lot of data in these tables.
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
)