Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the time difference between of two rows

Tags:

I have a table with column StartDate, I want to calculate the time difference between two consecutive record.

Thanks.


@ Mark Byers and @ Yahia, I have request table as requestId, startdate

requestId    startdate                1            2011-10-16 13:15:56 2            2011-10-16 13:15:59 3            2011-10-16 13:15:59 4            2011-10-16 13:16:02 5            2011-10-16 13:18:07 

and i want to know what is the time difference between requestid 1 & 2, 2 & 3, 3 & 4 and so on. i know i will need self join on table, but i am not getting correct on clause.

like image 507
user1019444 Avatar asked Oct 29 '11 06:10

user1019444


People also ask

How do I find the difference between two rows in SQL?

In the blue text, you can see the calculation of the SQL delta between two rows. To calculate a difference, you need a pair of records; those two records are “the current record” and “the previous year's record”. You obtain this record using the LAG() window function.

How do I compare two consecutive rows in SQL?

Here's the SQL query to compare each row with previous row. In the above query, we join sales table with itself using an INNER JOIN condition g2.id=g1.id + 1 that allows you to compare each row with its previous row. Please note, this condition depends on the fact that our id column has consecutive numbers.

How can I find the difference between two timestamps in SQL?

To calculate the difference between the timestamps in MySQL, use the TIMESTAMPDIFF(unit, start, end) function. The unit argument can be MICROSECOND , SECOND , MINUTE , HOUR , DAY , WEEK , MONTH , QUARTER , or YEAR .


2 Answers

The accepted answer is correct but gives the difference of numbers. As an example if I have the following 2 timestamps:

2014-06-09 09:48:15 2014-06-09 09:50:11 

The difference is given as 196. This is simply 5011 - 4815. In order to get the time difference, you may modify the script as follows:

SELECT A.requestid, A.starttime, TIMESTAMPDIFF(MINUTE,A.starttime,B.starttime) AS timedifference  FROM MyTable A INNER JOIN MyTable B ON B.requestid = (A.requestid + 1)  ORDER BY A.requestid ASC 
like image 26
kalan nawarathne Avatar answered Sep 30 '22 09:09

kalan nawarathne


To achieve what you are asking try the following (UPDATE after edit from OP):

SELECT A.requestid, A.starttime, (B.starttime - A.starttime) AS timedifference FROM MyTable A INNER JOIN MyTable B ON B.requestid = (A.requestid + 1) ORDER BY A.requestid ASC 

IF requestid is not consecutive then you can use

SELECT A.requestid, A.starttime, (B.starttime - A.starttime) AS timedifference FROM MyTable A CROSS JOIN MyTable B WHERE B.requestid IN (SELECT MIN (C.requestid) FROM MyTable C WHERE C.requestid > A.requestid) ORDER BY A.requestid ASC 
like image 103
Yahia Avatar answered Sep 30 '22 09:09

Yahia