Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如何选择计数不同的(唯一的卡车司机),无需按功能分组,也可能无需使用Having(不确定最后一个)_Mysql_Sql - Fatal编程技术网

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                
    
  • 我需要SQL查询,以获取2020年6月从伦敦市往返一次以上的所有独特卡车司机的数量。
    在同一个查询中,提取这些旅行中发生事故的人数

    我尝试的例子

    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
    子句有助于实现这一点

    台阶
  • 查找2020年6月往返伦敦的旅行。您可以使用
    中的
    存在的
    查看旅行是否发生事故
  • 按旅行者分组伦敦旅行,统计旅行和意外旅行,只保留那些有一次以上旅行的旅行者
  • 使用此结果集统计旅行者并总结他们的旅行
  • 查询 如果您的MySQL版本不支持带有
    子句的
    ,您当然可以嵌套查询

    with a as (...), b as (... from a) select * from b;
    
    变成

    select * from (... from (...) a) b;
    

    你在请求标题中说你不想在查询中使用
    groupby
    。这是可能的,但会使查询更加复杂。如果你想这样做,我将此作为一项任务留给你。提示:你可以选择旅行者并在每个旅行者的子查询中计数。

    为什么你在标题中说不能使用
    groupby
    另一方面,你可能想把这个国家限制在英格兰,因为世界上还有其他同名城市()。
    select * from (... from (...) a) b;