简体   繁体   中英

Find a gap between time stamp

I have many many rows in the table. The table has a Date column (which includes date and time)

I want to be able to loop through the table and find any gap between the two rows where the difference between the row is 5 min.

For example:

ID Date
1 2014-07-29 13:00:00
2 2014-07-29 13:01:00
3 2014-07-29 13:07:00

So as you can see the time difference between the first row and second row is 1 min so I ignore, then I should be checking the time between the second row and third row. Since the time difference is 6 min I want to spit out an exception with the dates that were compared.

The table could contain many rows, so I would go and check the next record to the previous one and so one...

How could I achieve this in SQL Server. I can do a datediff, but I will have a lot of rows and I don't want to perform this manually.

Any suggestions?

NOTE* I don't need to worry about the cross over of hours from one day to another, since this task is only going to be used for a single day. I will specify on SQL statement where date = getdate()

One way to do it

WITH ordered AS
(
  SELECT *, ROW_NUMBER() OVER (ORDER BY date) rn
    FROM table1 
)
SELECT o1.id id1, o1.date date1, o2.id id2, o2.date date2, DATEDIFF(s, o1.date, o2.date) diff
  FROM ordered o1 JOIN ordered o2
    ON o1.rn + 1 = o2.rn 
 WHERE DATEDIFF(s, o1.date, o2.date) > 60

Output:

| ID1 |                       DATE1 | ID2 |                       DATE2 | DIFF |
|-----|-----------------------------|-----|-----------------------------|------|
|   2 | July, 29 2014 13:01:00+0000 |   3 | July, 29 2014 13:07:00+0000 |  360 |

Here is SQLFiddle demo

Since you are on SQL Server 2012, you can make use of the LEAD and LAG functions, like so:

;with cte as
(select id, 
 [date], 
 datediff(minute,[date],lead([date],1,0) over (order by [date])) difference,
 row_number() over (order by [date]) rn
from tbl)

select * from cte
where rn <> 1 --Skip first row ordered by the date
and difference > 5

This will return all rows which have a difference of more than 5 minutes with the next row. The assumption is that the rows are sorted in ascending order of date.

Demo

If you can leverage the ID column being ascending and incrementing by one:

select a.id, b.id, a.date, b.date
  from mytable a
  join mytable b
    on b.id = a.id - 1
 where datediff(minute, a.date, b.date) < 5

If you cannot leverage that:

with x as (
select row_number() over(order by date) as rownum, date
  from mytable
)
select a.rownum, b.rownum, a.date, b.date
  from x a
  join x b
    on b.rownum = a.rownum - 1
 where datediff(minute, a.date, b.date) < 5

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