问题描述
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
限制为一行。