简体   繁体   English

SQL查询对列的总和进行排序

[英]SQL query to order sum of a column

I have the following tables:我有以下表格:

Drivers table, with a Driver_Code column Drivers 表,带有 Driver_Code 列

Route_files table, with a Driver_Code column and a Route_Code column Route_files 表,包含 Driver_Code 列和 Route_Code 列

Routes table, with a Route_Code column and a Kilometers column Routes 表,包含 Route_Code 列和 Kilometers 列

For every entry in the Drivers table there may be more than 1 entry in the Route_files table with the same Driver_Code.对于 Drivers 表中的每个条目,Route_files 表中可能有超过 1 个具有相同 Driver_Code 的条目。 For every entry in the Route_files table, there is only one entry in the Routes table with the same Route_Code.对于 Route_files 表中的每个条目,Routes 表中只有一个具有相同 Route_Code 的条目。

What I am trying to do is order the Drivers based on the total number of kilometers that they drove.我要做的是根据他们驾驶的总公里数来订购司机。 So if I have the following data:因此,如果我有以下数据:

Drivers:驱动程序:

Driver_Code
2
3
4

Route_files:路线文件:

Driver_Code Route_Code
2           20
2           50
2           30
3           30
4           40

Routes:路线:

Route_Code Kilometers
20         1231
30         9
40         400000
50         24234

Then Driver 2 drove routes 20 30 and 50 so the total kilometers is 25474. Similarly driver 3 drove 9km and driver 4 drove 400000. The SQL query that I need should output:然后司机 2 驾驶路线 20 30 和 50,因此总公里数为 25474。同样,司机 3 开了 9 公里,司机 4 开了 400000。我需要的 SQL 查询应该输出:

Driver_Code Total_km
4           400000
2           25474
3           9

I tried to use an inner join on the Route_files and Routes tables to obtain a single "table" with all the necessary information, hoping that I could further use this obtained table, but couldn't figure out how to do that.我尝试在 Route_files 和 Routes 表上使用内部连接来获得一个包含所有必要信息的“表”,希望我可以进一步使用这个获得的表,但不知道该怎么做。 I am working in dBase 2019(and can't change to something better, unfortunately).我在 dBase 2019 工作(不幸的是,无法更改为更好的东西)。 Any hints and ideas are appreciated!任何提示和想法表示赞赏!

I finally managed to do it.我终于设法做到了。 This is the working query:这是工作查询:

select 
  Driver_Code, 
  SUM(km) as Total_km 
from 
  Route_files 
  inner join Routes on Route_files.Route_Code = Routes.Route_Codes 
GROUP BY 
  Route_files.Driver_Code 
ORDER BY 
  Total_km Descending

Initially I was doing select Driver_Code, km, SUM(km) and when trying to do GROUP BY, dBase was forcing me to group by Driver_Code as well as km, which meant that the SUM function was being applied to every single entry instead of on all the entries of a single Driver_Code, which is what I needed.最初我select Driver_Code, km, SUM(km) ,当尝试进行 GROUP BY 时,dBase 迫使我按 Driver_Code 和 km 进行分组,这意味着 SUM 函数被应用于每个条目而不是 on单个 Driver_Code 的所有条目,这是我需要的。 Now I finally understand what GROUP BY does!现在我终于明白 GROUP BY 是做什么的了!

Thanks everyone for your comments!感谢大家的意见!

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

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