Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a gap between time stamp

Tags:

sql

sql-server

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()

like image 542
smr5 Avatar asked Jul 30 '14 02:07

smr5


2 Answers

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

like image 124
peterm Avatar answered Oct 30 '22 02:10

peterm


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

like image 4
shree.pat18 Avatar answered Oct 30 '22 03:10

shree.pat18