Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference of datetime column in SQL

Tags:

sql

datetime

I have a table of 20000 records. each Record has a datetime field. I want to select all records where gap between one record and subsequent record is more than one hour [condition to be applied on datetime field].

can any one give me the SQL command code for this purpose.

regards

KAM

like image 659
KhawarAmeerMalik Avatar asked Jul 05 '26 14:07

KhawarAmeerMalik


2 Answers

ANSI SQL supports the lead() function. However, date/time functions vary by database. The following is the logic you want, although the exact syntax varies, depending on the database:

select t.*
from (select t.*,
             lead(datetimefield) over (order by datetimefield) as next_datetimefield
      from t
     ) t
where datetimefield + interval '1 hour' < next_datetimefield;

Note: In Teradata, the where would be:

where datetimefield + interval '1' hour < next_datetimefield;
like image 73
Gordon Linoff Avatar answered Jul 08 '26 03:07

Gordon Linoff


This can also be done with a sub query, which should work on all DBMS. As gordon said, date/time functions are different in every one.

SELECT t.* FROM YourTable t
WHERE t.DateCol + interval '1 hour' < (SELECT min(s.DateCol) FROM YourTable s
                   WHERE t.ID = s.ID AND s.DateCol > t.DateCol)

You can replace this:

t.DateCol + interval '1 hour'

With one of this so it will work on almost every DBMS:

DATE_ADD( t.DateCol, INTERVAL 1 hour)
DATEADD(hour,1,t.DateCol)
like image 25
sagi Avatar answered Jul 08 '26 03:07

sagi



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!