enter image description here如下图所示,我们有6条相同的vehicle_id记录(3 IN,3 OUT在不同的日期)。 我需要的结果是:
ID vehicle_id IN OUT
1 X first_record second_record
2 x third_record fourth_record
3 x fifth_record sixth_record
所以,一次记录一个输入时间和一个输出时间。
是否可以通过选择查询获得?还是需要编写一个存储过程?
答案 0 :(得分:0)
您可以使用带有限制子句的子查询
drop table if exists t;
create table t(id int auto_increment primary key, vid int, trip_status varchar(3),dt datetime);
insert into t (vid,trip_status,dt)
values
(1,'in','2018-12-01 01:00:00'),
(1,'out','2018-12-01 02:00:00'),
(1,'in','2018-12-01 03:00:00'),
(1,'out','2018-12-01 04:00:00'),
(1,'in','2018-12-01 05:00:00'),
(1,'in','2018-12-01 05:00:00');
select t.*
, (select case when t1.trip_status ='out' then trip_status
else concat(t1.trip_status, '**Error**')
end
from t t1 where t1.vid = t.vid and t1.id > t.id order by t1.id limit 1) nexttrip_status
, (select t1.dt from t t1 where t1.vid = t.vid and t1.id > t.id order by t1.id limit 1) next_dt
from t where trip_status = 'in';
+----+------+-------------+---------------------+-----------------+---------------------+
| id | vid | trip_status | dt | nexttrip_status | next_dt |
+----+------+-------------+---------------------+-----------------+---------------------+
| 1 | 1 | in | 2018-12-01 01:00:00 | out | 2018-12-01 02:00:00 |
| 3 | 1 | in | 2018-12-01 03:00:00 | out | 2018-12-01 04:00:00 |
| 5 | 1 | in | 2018-12-01 05:00:00 | in**Error** | 2018-12-01 05:00:00 |
| 6 | 1 | in | 2018-12-01 05:00:00 | NULL | NULL |
+----+------+-------------+---------------------+-----------------+---------------------+
4 rows in set (0.00 sec)
答案 1 :(得分:0)
Click here此图根据您的问题显示sql记录
这是您期望的输出。 SQL =“选择x.id,x.vehicle_id,x.time作为in_time,(从xx.new_table中选择y.time作为y,其中y.id = x.id + 1)作为从xx.new_table中作为x的超时,其中x .id%2 = 1“ 请注意“其中x.id%2 = 1”的这种情况,您必须使其动态。有时您必须根据记录的ID设置= 0或= 1。为此,您需要编写加法选择SQL进行检查。希望这会帮助你。
Click Here要查看输出屏幕截图