I have the following table (scores
):
id user date score
---|-----|------------|--------
1 | 10 | 11/01/2016 | 400
2 | 10 | 11/03/2016 | 450
5 | 17 | 10/03/2016 | 305
3 | 13 | 09/03/2016 | 120
4 | 17 | 11/03/2016 | 300
6 | 13 | 08/03/2016 | 120
7 | 13 | 11/12/2016 | 120
8 | 13 | 09/01/2016 | 110
I want to select max(score)
for each distinct user, using date
as a tie-breaker (in the event of a tie, the most recent record should be returned) such that the results look like the following (top score for each user, sorted by score
in descending order):
id user date score
---|-----|------------|--------
2 | 10 | 11/03/2016 | 450
5 | 17 | 10/03/2016 | 305
7 | 13 | 11/12/2016 | 120
I'm using Postgres and I am not a SQL expert by any means. I've tried something similar to the following, which doesn't work because I don't have the id
column included in the group by
:
select scores.user, max(scores.score) as score, scores.id
from scores
group by scores.user
order by score desc
I have a feeling I need to do a sub-select, but I can't get the join to work correctly. I found How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL? but I can't seem to make any of the solutions work for me because I need to return the row's id
and I have the possibility of a tie on the date
column.