Mysql 如何选择计数不同的(唯一的卡车司机),无需按功能分组,也可能无需使用Having(不确定最后一个)
我有一项任务,但无法解决: 有卡车司机,他们必须往返于城市之间。Mysql 如何选择计数不同的(唯一的卡车司机),无需按功能分组,也可能无需使用Having(不确定最后一个),mysql,sql,Mysql,Sql,我有一项任务,但无法解决: 有卡车司机,他们必须往返于城市之间。 我们的数据库中有两个表中的这些旅行数据: 卡车司机 tt_id (key) date starting_point_coordinate destination_coordinate traveller_id event_type ('travel', 'acc
我们的数据库中有两个表中的这些旅行数据:
tt_id (key)
date
starting_point_coordinate
destination_coordinate
traveller_id
event_type ('travel', 'accident')
parent_event_id (For 'accident' event type it's tt_id of the original travel. There might be few accidents within one travel.)
coordinate (key)
country
city
在同一个查询中,提取这些旅行中发生事故的人数 我尝试的例子
SELECT
count(distinct(tt.traveller_id)),
FROM trucker_traffic tt
JOIN trucker_places tp
ON tt.starting_point_coordinate = tp.coordinate
OR tt.destination_coordinate = tp.coordinate
WHERE
tp.city = 'London'
AND month(tt.date) = 6
AND year(tt.date) = 2020
GROUP BY tt.traveller_id
HAVING count(tt.tt_id) > 1
但它是选择计数不同的卡车司机分组和工作,只有当我有一个跟踪数据库
对于任务的第二部分(我选择了带事故的旅行次数),我认为使用这样的功能很好
SUM(if(count(tt_id = parent_event_id),1,0))
但我不确定这是否相当复杂,所以请确保一步一步地执行。
WITH
子句有助于实现这一点
台阶
中的或存在的查看旅行是否发生事故
,您当然可以嵌套查询
with a as (...), b as (... from a) select * from b;
变成
select * from (... from (...) a) b;
你在请求标题中说你不想在查询中使用groupby
。这是可能的,但会使查询更加复杂。如果你想这样做,我将此作为一项任务留给你。提示:你可以选择旅行者并在每个旅行者的子查询中计数。为什么你在标题中说不能使用groupby
另一方面,你可能想把这个国家限制在英格兰,因为世界上还有其他同名城市()。
select * from (... from (...) a) b;