0

SQL query: 3 column table, searching "John" 's max value returning City only.
Data:
Name | City | Value <br>
John | LDN | 50 <br>
Joey | MCR | 12<br>
Dave | BHM | 5<br>
John | NTH | 56 <br>

Desired result: NTH (4th row)

How can I achieve this? Thanks in advance.

Fahmi
  • 37,315
  • 5
  • 22
  • 31
braxofribz
  • 11
  • 2
  • 1
    Which dbms are you using? – jarlh Aug 24 '20 at 10:41
  • 1
    What would be the expected result if John, LDN also had 56? – jarlh Aug 24 '20 at 10:42
  • T-SQL. If John, LDN has 56? Luckily I'm not too worried about this but it does raise a good point as to what would take priority! – braxofribz Aug 24 '20 at 11:50
  • Possible duplicate of [TSQL show only first row](https://stackoverflow.com/questions/12688576/tsql-show-only-first-row). Just order by Value instead of Date. In [how does SELECT TOP works when no order by is specified?](https://stackoverflow.com/questions/15245322/how-does-select-top-works-when-no-order-by-is-specified) the answer is in the Question and in [Select Top N Records Ordered by X, But Have Results in Reverse Order](https://stackoverflow.com/questions/2572496/select-top-n-records-ordered-by-x-but-have-results-in-reverse-order) the answer is in the subquery. – Scratte Aug 26 '20 at 06:27

2 Answers2

0

You can use 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'

Alternatively,

select city from tablename t 
where name='John' and value = (select max(value) from tablename t1 where t.name=t1.name)
Fahmi
  • 37,315
  • 5
  • 22
  • 31
0

You can use order by and some way of limiting the results:

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

Some databases use select top (1) or limit 1 to limit to a single row.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786