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.
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.
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.
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 .
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With