SQL-查找最大值,然后查找对应的列

问题描述


SQL查询:3列表,搜索“ John”的最大值,仅返回City。
数据:
Name | City | Value <br>
John | LDN | 50 <br>
Joey | MCR | 12<br>
Dave | BHM | 5<br>
John | NTH | 56 <br>

期望的结果:NTH(第4行)

我该如何实现?预先感谢。

解决方法

您可以使用row_number()

select city from
(
select *,row_number() over(partition by name order by value desc) as rn
from tablename
)A where rn=1 and name='John'

或者,

select city from tablename t 
where name='John' and value = (select max(value) from tablename t1 where t.name=t1.name)
,

您可以使用order by和一些限制结果的方法:

select t.*
from t
order by value desc
fetch first 1 row only;

某些数据库使用select top (1)limit 1限制为一行。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...