I have a table containing a list of datetimes.
I would like to find the longest time span between consecutive dates, i.e. Find the largest distance between any two date and time records that fall next to each other on the timeline. Think of it as the “longest strip” —the longest time from one reset to the next in chronological order.
For exmaple:
mysql> select * from resets order by datetime asc; +----+---------------------+-------------+---------------------+---------------------+ | id | datetime | activity_id | created_at | updated_at | +----+---------------------+-------------+---------------------+---------------------+ | 7 | 2014-12-30 20:38:22 | 1 | 2015-01-06 20:38:22 | 2015-01-06 20:38:22 | | 3 | 2014-12-31 20:38:22 | 1 | 2015-01-06 20:38:22 | 2015-01-06 20:38:22 | | 5 | 2015-01-01 20:38:22 | 1 | 2015-01-06 20:38:22 | 2015-01-06 20:38:22 | | 4 | 2015-01-02 20:38:22 | 1 | 2015-01-06 20:38:22 | 2015-01-06 20:38:22 | | 6 | 2015-01-03 20:38:22 | 1 | 2015-01-06 20:38:22 | 2015-01-06 20:38:22 | | 1 | 2015-01-04 20:38:22 | 1 | 2015-01-06 20:38:22 | 2015-01-06 20:38:22 | | 2 | 2015-01-05 20:38:22 | 1 | 2015-01-06 20:38:22 | 2015-01-06 20:38:22 | etc...
From the sample dataset above, I want to know which of the following time differences is greater:
- between lines 7 and 3
- between lines 3 and 5
- between lines 5 and 4
- etc...
(Obviously, they are all in exactly 24 hours. I’m looking for a common solution.)
This is easily done using a common programming language by iterating over an ordered array, preserving the differences between consecutive values, and choosing the largest one.
Is there an easy way to do this using only SQL?
Update:
The request that worked for me was
SELECT MAX(DATEDIFF(r.next_datetime, r.datetime)) FROM (
The innermost SELECT datetime FROM resets r2... query SELECT datetime FROM resets r2... is responsible for finding the next datetime in a list that is larger than the current one. Please note that this request is streamlined and has a restriction of 1. This was the hardest part for me.
The rest is pretty simple. For each row in the table, we select the datetime value and the next sequential datetime in the table. The outermost query finds the biggest difference between any of the datetime data pairs that we just created - a "winning stroke".
I chose the answer that @OllieJones gave because it was the most accurate and best explanation, even if I prefer the "pure SQL" solution.