简体   繁体   中英

SQL - Get top value for each user (DISTINCT ?)

I have a MySQL table containing userID , score .
A single user can have many scores, but there can be many users, of course.

I want to retrieve the highest score for-each of the userID 's in the database.

I've tried the following but I feel like i'm in the wrong way :

SELECT DISTINCT(`userID`), `score` FROM `myTable` ORDER BY `score` DESC

Any assistance will be greatly appreciated.

Thanks
Shai.

You want the aggregate function max with the group by clause:

select
    userid,
    max(score) as maxscore
from
    mytable
group by userid
order by maxscore desc

The group by says, "Hey, MySQL, get me the max score , but partition it by userid ." This way, you get the max score for each userid .

Additionally, you can order by the aliased column so you get the list of users by max score, descending (for a leaderboard or what have you).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM