Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - How to select rows with max value of a field

Tags:

sql

mysql

I have a table of users with their scores for each level of a game:

id | user_id | level | score
1  | David   | 1     | 20
2  | John    | 1     | 40
3  | John    | 2     | 30
4  | Mark    | 1     | 60
5  | David   | 2     | 10
6  | David   | 3     | 80
7  | Mark    | 2     | 20
8  | John    | 3     | 70
9  | David   | 4     | 50
10 | John    | 4     | 30

What is the SQL query needed to get for each level, who has the highest score?

The result should be:

id | user_id | level | score
4  | Mark    | 1     | 60
3  | John    | 2     | 30
6  | David   | 3     | 80
9  | David   | 4     | 50

Thank you

like image 875
Mr. Messy Avatar asked Nov 04 '16 01:11

Mr. Messy


1 Answers

If you want to get ties, then you can do something like this:

select s.*
from scores s
where s.score = (select max(s2.score) from scores s2 where s2.level = s.level);

You could get one row per level by aggregating this:

select s.level, s.score, group_concat(s.user_id)
from scores s
where s.score = (select max(s2.score) from scores s2 where s2.level = s.level)
group by s.level, s.score;

This combines the users (if there is more than one) into a single field.

like image 119
Gordon Linoff Avatar answered Sep 22 '22 05:09

Gordon Linoff