如何计算所有ID相同的行中的列?

时间:2019-03-02 08:49:49

标签: php sql laravel

我有一个表3表:usersres_inforeservations

我想计算每个驾驶员从最高公里到最低公里的路程。

在字段total_kms中,我想显示每个驾驶员的总公里数:例如Mohamed Mostafa切割距离550和323 km

以下信息将显示在表中:

name  ----------------   |    total kms    
mohamed mostafa          |     873

这是我尝试过的代码:

select 
    users.name, count(res_info.res_id) as total_drives,
    (reservations.meters + reservations.meters) as   total_kms,
    reservations.meters as kms 
from 
    reservations 
    left outer join res_info 
        on (reservations.id=res_info.res_id) 
    left outer join users on (reservations.driver_id=users.id) 
where 
    reservations.zone_id = 2 
    and reservations.meters !='' 
group by 
    res_info.res_id 
order by 
    count(res_info.res_id) desc

1 个答案:

答案 0 :(得分:0)

您不再需要reservations.meters as kms,因为它破坏了SUM上的分组。而且您需要按SUM而不是计数进行订购,因为您想按驾驶员行进的最大距离进行订购。这是您需要的:

select 
    users.name, count(res_info.res_id) as total_drives,
    sum(reservations.meters + reservations.meters) as total_kms
from 
    reservations 
    left outer join res_info 
        on (reservations.id=res_info.res_id) 
    left outer join users on (reservations.driver_id=users.id) 
where 
    reservations.zone_id = 2 
    and reservations.meters !='' 
group by 
    users.name 
order by 
    total_kms desc