我是SQL的新手,所以经过多次尝试后,我无法在Stackoverflow上找到合适的解决方案。这就是为什么我发布了我的问题。[可能这是一个重复的问题]我有2个表Driver和Ride。结构如下:
表:
Person:
id Name Email reg_number
37 test1 [email protected] 111111
38 test2 [email protected] 222222
39 test3 [email protected] 333333
40 test4 [email protected] 444444
41 test5 [email protected] 555555
42 test6 [email protected] 666666
Rides:
id Person_id start_time end_time distance
23 38 2018-08-08T12:12:12 2018-08-08T13:12:12 1000
24 39 2018-08-08T12:12:12 2018-08-08T14:12:12 1100
25 40 2018-08-08T12:12:12 2018-08-08T13:12:12 1200
26 41 2018-08-08T12:12:12 2018-08-08T15:12:12 1300
27 42 2018-08-08T12:12:12 2018-08-08T15:12:12 600
28 42 2018-08-08T12:12:12 2018-08-08T13:12:12 700
29 41 2018-08-08T12:12:12 2018-08-08T16:12:12 800
我的查询是:人是乘坐出租车的司机。
start_time是他骑行的开始时间。 end_time是他骑行的结束时间。距离是KM的距离。
我想将开始和结束时间传递给查询。
结果应该包括TOP 5人员的电子邮件,姓名,骑行总分钟数,最长骑行时间(分钟)。
只应计算在上述持续时间内开始和结束的游乐设施。
注意:一个人所有游乐设施的总分钟数是TOP的标准。
众所周知,日期/时间函数取决于数据库。您需要标记正在使用的数据库。
我假设您正在使用MySQL。
您只需使用rides
表即可回答“前5名”:
select r.person_id,
sum(to_seconds(r.end_time) - to_seconds(r.start_time)) as duration_seconds
from rides r
where r.start_time >= ? and
r.end_time <= ?
group by r.person_id
order by duration_seconds desc
limit 5;
这基本上就是你想要的。现在您只需要添加person
信息并将秒转换为分钟:
select p.*, top5.duration_seconds / 60 as duration_minutes
from (select r.person_id,
sum(to_seconds(r.end_time) - to_seconds(r.start_time)) as duration_seconds
from rides r
where r.start_time >= ? and
r.end_time <= ?
group by r.person_id
order by duration_seconds desc
limit 5
) top5 join
person p
on top5.person_id = p.id;
其他数据库有其他方法来提取两个datetime
值之间的持续时间。
?
是定义时间范围的值的占位符。