[英]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:我有一个选择 taht 带来这样的结果:
+-----------+------------+--------------+
| 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:正如您所看到的,ID 不遵循线性顺序,但是我真正需要的是一个选择,它为我带来最后一次插入的新start_time和end_time之间的时间,遵循这个非线性顺序,所以我需要一个选择我这个:
+-----------+------------+--------------+----------------+
| 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.任何解决它的方法都会有所帮助。
For this sample data you can use timediff()
function:对于此示例数据,您可以使用timediff()
函数:
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 |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.