简体   繁体   English

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

[英]How to count columns from all rows where it equals the same id?

I have a table 3 table: users , res_info , reservations 我有一个表3表: usersres_inforeservations

I want to calculate the number of kilometers traveled by each driver in the trip from the highest kilometer to the lowest. 我想计算每个司机从最高公里到最低公里的路程。

In field total_kms , I want to display the total kilometers per driver: for example Mohamed Mostafa Cutting distance 550 and 323 km 在字段total_kms ,我想显示每个驾驶员的总公里数:例如Mohamed Mostafa切割距离550和323 km

The following information will be displayed in the table: 下表中将显示以下信息:

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

This my code i have tried : 这是我尝试过的代码:

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

You don't need reservations.meters as kms anymore because it's breaking the grouping on the SUM. 您不再需要reservations.meters as kms ,因为它打破了SUM上的分组。 And you need to order by SUM instead of count since you want to order by most distance traveled by driver. 而且您需要按SUM而不是计数进行订购,因为您想按驾驶员行进的最大距离进行订购。 Here is what you need : 这是您需要的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM