Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres difference between time stamp in minutes

I am trying to get time difference in minutes between the event time of below data having the same nodeid and code for nodeid having count > 1

nodeid  code     event_time
CAI0015 14961045 2017-04-22 21:22:00
CAI0024 14961045 2017-04-23 19:44:00
CAI0024 14961045 2017-04-23 09:07:00
CAI0040 14971047 2017-04-23 13:58:00
CAI0046 14961045 2017-04-23 11:19:00
CAI0050 14961045 2017-04-24 02:06:00

output should be like this:

nodeid  code     difference(min)
CAI0024 14961045 637
like image 425
Helmy Avatar asked Jul 17 '26 10:07

Helmy


2 Answers

Use the formula extract(epoch from <later> - <earlier>) / 60 to get timestamp difference in minutes.

To select all permutations of differences (where nodeid & code is the same) within the table, use a self-join:

select nodeid, code, extract(epoch from e2.event_time - e1.event_time) / 60 difference
from   events e1
join   events e2 using (nodeid, code)
where  e1.event_time < e2.event_time

However, this seems not to be actually useful, when you have more than 2 rows for a given nodeid & code pair. To calculate difference for the previous ones only, use the lag() window function:

select nodeid, code, extract(epoch from event_time - lag) / 60 difference
from   (select *, lag(event_time) over (partition by nodeid, code order by event_time)
        from   events) e
where  lag is not null

http://rextester.com/HGY2600

Note: both of these will give you only one row for every nodeid & code pair, if you only have max 2 rows for all of the pairs.

like image 124
pozs Avatar answered Jul 18 '26 23:07

pozs


try to use dense_rank to find the next event.

SELECT t_a.*, EXTRACT(EPOCH FROM (t_a.event_time - t_b.event_time))
FROM 
(SELECT nodeid, code, event_time, dense_rank() over (partition by node_id order by event_time) as rnk
 FROM table) t_a 
JOIN
(SELECT nodeid, code, event_time, dense_rank() over (partition by node_id order by event_time) as rnk 
 FROM table) t_b 
ON (t_a.nodeid=t_b.nodeid and t_a.rnk + 1 = t_b.rnk)
like image 27
Yaron Neuman Avatar answered Jul 19 '26 01:07

Yaron Neuman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!