简体   繁体   中英

SQL - How to find difference between two rows of same column containing timestamps

I have a table name as test containing below two colums

name    GMTtime
Test1   2019-02-01 19:54:45.507
Test2   2019-02-15 19:54:55.537
Test3   2019-02-15 19:55:05.560
Test4   2019-02-15 19:55:15.580

Question : I want to list rows of GMTtime if difference between these timestamps are more than 15secs (eg diff between "2019-02-01 19:54:45.507" and 2019-02-15 19:54:55.537 is not more than 15seconds)

In standard SQL, you would use lag() and date comparisons:

select t.*
from (select t.*, lag(t.GMTtime) over (order by t.GMTtime) as prev_GMTtime
      from t
     ) t
where prev_GMTtime < GMTtime - interval '15 second'

使用函数: from_unixtime()

If you're running MySQL 5.7 or below (ie a version of SQL that doesn't support LAG ), you can get the results you need by JOIN ing your table to itself using the condition that the time for the second table is the latest time less than the time from the first table. Then you can compare the two times using TIMESTAMPDIFF to find those more than 15 seconds apart:

SELECT *
FROM test t1
JOIN test t2 ON t2.GMTtime = (SELECT MAX(GMTtime) 
                              FROM test 
                              WHERE test.GMTtime < t1.GMTtime)
WHERE TIMESTAMPDIFF(SECOND, t2.GMTtime, t1.GMTtime) > 15

Output:

name   GMTtime               name   GMTtime
Test2  2019-02-15 19:54:56   Test1  2019-02-01 19:54:46

Demo on dbfiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM