0

I have a table which looks like

phoneNumber | City      | totalPoints
12345678    | Singapore | 2000
12345679    | Singapore | 3000
23456789    | New York  | 2100
12312312    | New York  | 2200
12312343    | Beijing   | 4000

And I want to get result like

phoneNumber | City      | totalPoints
12345679    | Singapore | 3000
12312312    | New York  | 2200
12312343    | Beijing   | 4000

Just select the row which has the maximun value of totalPoints in each city. How to write the SQL code? (I am using MS SQL Server)

0

1 Answer 1

3

In sql-server :

select * from
(
select *,rn=row_number()over(partition by City order by totalpoints desc) from table
)x
where rn=1
Sign up to request clarification or add additional context in comments.

3 Comments

Hi, thank you! It works but it looks quite odd. I try MAX() and GROUP BY but it seems this cannot work in this case. Any better solutions? Or do I have to change my database design?
you cannot use a max() if you did then you need to group by ... so in this case this only way left !
oops.. i missed this part.. why you say "It works but it looks quite odd."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.