João Amaro
João Amaro

Reputation: 496

How to DATEDIFF in MySQL between two consecutive rows not having consecutive IDs?

Currently I have a query giving me this results coming from table "Logs":

S.ID    S.INDEX   E.ID  TIME                      Secs
1       1         1     2018-05-14 16:07:48.527   
2       2         1     2018-05-14 16:08:02.967   14
3       3         1     2018-05-14 16:08:21.750   19
10      1         2     2018-05-14 16:07:46.983
11      2         2     2018-05-14 16:08:00.883   14
12      3         2     2018-05-14 16:09:19.830   79
13      4         2     2018-05-14 16:09:49.907   30
29      1         3     2018-05-14 16:08:02.490
30      2         3     2018-05-14 16:08:06.717   04

The column "Secs" was wrote by hand here, those are the values I need. Already tried to use DATEDIFF but since S.ID is not consecutive (it depends on E.ID) I'm not getting the right results.

How can I make a query to return the right values? I imagine I should take E.ID in consideration since it's the only thing that remains the same during the "same" incrementation and that if I see a 1 in S.INDEX I should reset counting.

Upvotes: 0

Views: 62

Answers (1)

Uueerdo
Uueerdo

Reputation: 15941

This should work, as long as the pattern I described in my original comment is guaranteed:

SELECT a.*, TO_SECONDS(a.TIME) - TO_SECONDS(b.TIME) AS `Secs`
FROM theTable AS s
LEFT JOIN theTable AS b ON a.`e.id` = b.`e.id` AND a.`s.id` = b.`s.id` + 1
;

Additionally, if there is always a gap between different e.id value's s.id values, the e.id comparison is not actually needed, though still makes the intent of the query clearer.

Upvotes: 1

Related Questions