SQL Group By and min (MySQL)(SQL Group By 和 min (MySQL))
问题描述
我有以下 SQL:
select code, distance from places;
输出如下:
CODE DISTANCE LOCATION
106 386.895834130068 New York, NY
80 2116.6747774121 Washington, DC
80 2117.61925131453 Alexandria, VA
106 2563.46708627407 Charlotte, NC
我希望能够只获得一个代码和最近的距离.所以我希望它返回这个:
I want to be able to just get a single code and the closest distance. So I want it to return this:
CODE DISTANCE LOCATION
106 386.895834130068 New York, NY
80 2116.6747774121 Washington, DC
我最初有这样的事情:
SELECT code, min(distance), location
GROUP BY code
HAVING distance > 0
ORDER BY distance ASC
如果我不想获得与最小距离相关联的正确位置,则 min 工作正常.我如何获得最小(距离)和正确的位置(取决于表格中插入的顺序,有时您最终可能会得到纽约的距离,但最终会得到夏洛特的位置).
The min worked fine if I didn't want to get the correct location that was associated with the least distance. How do I get the min(distance) and the correct location (depending on the ordering on the inserts in the table, sometimes you could end up with the New York distance but the Charlotte in Location).
推荐答案
要获得正确的关联位置,您需要加入一个子选择,该子选择获取每个代码的最小距离,条件是外部主表中的距离与子选择中导出的最小距离匹配.
To get the correct associated location, you'll need to join a subselect which gets the minimum distance per code on the condition that the distance in the outer main table matches with the minimum distance derived in the subselect.
SELECT a.code, a.distance
FROM places a
INNER JOIN
(
SELECT code, MIN(distance) AS mindistance
FROM places
GROUP BY code
) b ON a.code = b.code AND a.distance = b.mindistance
ORDER BY a.distance
这篇关于SQL Group By 和 min (MySQL)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SQL Group By 和 min (MySQL)
基础教程推荐
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- 无法解决整理冲突 2021-01-01
