gpt4 book ai didi

mysql - 按顺序从两行中选择数据作为单行

转载 作者:行者123 更新时间:2023-11-29 16:30:50 25 4
gpt4 key购买 nike

enter image description here如下图所示,相同的vehicle_id有6条记录(不同日期有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

因此,对于一个记录,一个 IN 时间和一个 OUT 时间。

是否可以使用选择查询来获取,或者我是否需要编写存储过程?

最佳答案

例如,您可以使用带有限制子句的子查询

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)

关于mysql - 按顺序从两行中选择数据作为单行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53932980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com