jacob d davis
jacob d davis

Reputation: 55

MYSQL - How may i subtract two columns on two different rows, on the same table?

I have a select taht brings the result like this:

+-----------+------------+--------------+
| parking_id| start_time |   end_time   |
+-----------+------------+--------------+
|        38 | 09:15:00   | 10:32:00     |
|        57 | 11:45:00   | 13:21:00     |
|        33 | 14:40:00   | 16:35:00     |
|        15 | 17:13:00   | 19:15:00     |
|        68 | 20:54:00   | NULL         |
+-----------+------------+--------------+

As you can see the IDs dont follow a linear order, but wat i really need is a select that brings me the time between the new start_time and end_time for the last inserted , that follows this non linear order, so i need a select that brings me this:

+-----------+------------+--------------+----------------+
| parking_id| start_time |   end_time   | time_btw_parks |
+-----------+------------+--------------+----------------+
|        38 | 09:15:00   | 10:32:00     |     NULL       |
|        57 | 11:45:00   | 13:21:00     |   01:13:00     |
|        33 | 14:40:00   | 16:35:00     |   01:19:00     |
|        15 | 17:13:00   | 19:15:00     |   00:38:00     |
|        68 | 20:54:00   | NULL         |   01:39:00     |
+-----------+------------+--------------+----------------+

Doesn't have to necessary be select query. Anything that solves it would help.

Upvotes: 0

Views: 71

Answers (1)

forpas
forpas

Reputation: 164099

For this sample data you can use timediff() function:

select t.parking_id, t.start_time, t.end_time,
  timediff(t.start_time, max(tt.end_time)) time_btw_parks
from tablename t left join tablename tt
on t.start_time > tt.end_time 
group by t.parking_id, t.start_time, t.end_time
order by t.start_time

See the demo.
Results:

| parking_id | start_time | end_time | time_btw_parks |
| ---------- | ---------- | -------- | -------------- |
| 38         | 09:15:00   | 10:32:00 |                |
| 57         | 11:45:00   | 13:21:00 | 01:13:00       |
| 33         | 14:40:00   | 16:35:00 | 01:19:00       |
| 15         | 17:13:00   | 19:15:00 | 00:38:00       |
| 68         | 20:54:00   |          | 01:39:00       |

Upvotes: 1

Related Questions