Reputation: 99
I have a table similar to this:
+---------------+---------------------+---------------------+-----------------------+
| event_type_id | start_time | end_time | hours_from_last_event |
+---------------+---------------------+---------------------+-----------------------+
| 1 | 2019-06-07 0:00:00 | 2019-06-07 22:00:00 | |
| 1 | 2019-06-09 21:00:00 | 2019-06-09 23:00:00 | |
| 1 | 2019-06-10 16:00:00 | 2019-06-10 20:00:00 | |
| 2 | 2019-06-05 14:00:00 | 2019-06-05 19:00:00 | |
| 2 | 2019-06-07 03:00:00 | 2019-06-07 21:00:00 | |
+---------------+---------------------+---------------------+-----------------------+
For each row, I want to set hours_from_last_event
by subtracting the end_time
from the previous row from the start_time
of the current row ONLY when the event_type_id
are equal. If there is no previous row for that row, it should be NULL
.
So the above table would become:
+---------------+---------------------+---------------------+-----------------------+
| event_type_id | start_time | end_time | hours_from_last_event |
+---------------+---------------------+---------------------+-----------------------+
| 1 | 2019-06-07 0:00:00 | 2019-06-07 22:00:00 | NULL |
| 1 | 2019-06-09 21:00:00 | 2019-06-09 23:00:00 | 47 |
| 1 | 2019-06-10 16:00:00 | 2019-06-10 20:00:00 | 17 |
| 2 | 2019-06-05 14:00:00 | 2019-06-05 19:00:00 | NULL |
| 2 | 2019-06-07 03:00:00 | 2019-06-07 21:00:00 | 32 |
+---------------+---------------------+---------------------+-----------------------+
We can assume that an id
column exists to uniquely identify each row.
I already know I can use the TIMEDIFF()
function to find the difference in hours, but how should I go about doing this in MySQL?
Upvotes: 0
Views: 106
Reputation: 1269773
You can just use lag()
for this purpose:
select t.*,
timestampdiff(hour, lag(end_time) over (partition by event_type_id orde rby start_time), start_time) as diff
from t;
You cannot use this in an update
though . . . except through a join
:
update t join
(select t.*,
timestampdiff(hour, lag(end_time) over (partition by event_type_id order by start_time), start_time) as diff
from t
) tt
on tt.event_type_id = t.event_type_id and tt.start_time = t.start_time
set t.hours_from_last_event = tt.diff;
Upvotes: 1