Difference in time between records

馋奶兔 提交于 2019-12-05 08:33:49

This is Oracle 9i+, using the LAG function to get the previous timestamp value without needing to self join:

SELECT t.timestamp - LAG(t.timestamp) OVER (ORDER BY t.timestamp) AS diff
  FROM YOUR_TABLE t

...but because whole numbers represent the number of days in the result, a difference of less than 24 hours will be a fraction. Also, the LAG will return NULL if there's no earlier value -- same as if having used an OUTER JOIN.

To see minutes, use the ROUND function:

SELECT ROUND((t.timestamp - LAG(t.timestamp) OVER (ORDER BY t.timestamp)) *1440) AS diff_in_minutes
  FROM YOUR_TABLE t

If the records have sequential id's you could do a self join like this:

SELECT t2.*, t2.timestamp - t1.timestamp AS timediff
FROM foo t1 inner join foo.t2 on t1.id = t2.id-1

You'd probably need to tweak this to handle the first and last records, but that's the basics.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!