I’ve got a possibly ‘classic’ mysql max/group by question
Here is my basic table structure.
id | userid | username | date | score
1 | 1111 | joe | 2012-05-16 | 1000
2 | 2222 | john | 2012-03-17 | 2000
3 | 3333 | jill | 2012-02-11 | 3000
4 | 2222 | john | 2012-12-25 | 5000
5 | 3333 | jill | 2012-04-08 | 4000
6 | 1111 | joe | 2012-06-17 | 1000
7 | 1111 | joe | 2012-01-14 | 500
8 | 2222 | john | 2012-06-29 | 6000
9 | 4444 | bill | 2012-08-08 | 4000
I would like to get each user’s highest score.
Each user should have only one score displayed in the result.
My desired result is
id | userid | username | date | score
8 | 2222 | john | 2012-06-29 | 6000
9 | 4444 | bill | 2012-08-08 | 4000
5 | 3333 | jill | 2012-04-08 | 4000
6 | 1111 | joe | 2012-06-17 | 1000
If the user’s highest score appears more than once (ex id 1&6), the most recent date should be displayed.
This is my current query
select s.*
from scores as s
inner join (
select userid, max(score) as max_score
from scores
group by userid
) t on s.userid = t.userid and s.score = t.max_score
order by score DESC, date DESC
Which returns the incorrect result of
id | userid | username | date | score
8 | 2222 | john | 2012-06-29 | 6000
9 | 4444 | bill | 2012-08-08 | 4000
5 | 3333 | jill | 2012-04-08 | 4000
6 | 1111 | joe | 2012-06-17 | 1000
1 | 1111 | joe | 2012-05-16 | 1000
Any suggestions on how to resolve this?
I should also mention that the relationship between userid and username is not one to one.
This should give you the result you are looking for. Since MySql doesn’t have a
PARTITIONfunction as SQL SERVER, I used a known work around.