How can I get the rank of rows relative to total number of rows based on a field?
I have a scores
table that has two fields:
- user_id
- score
I'm fetching specific rows that match a list of user_id's. How can I determine a rank for each row relative to the total number of rows, based on score
? The rows in the result set are not necessarily sequential (the scores will vary widely from one row to the next). I'm not sure if this matters, but user_id
is a unique field.
Edit
@Greelmo
I'm already ordering the rows. If I fetch 15 rows, I don't want the rank to be 1-15. I need it to be the position of that row compared against the entire table by the score
property. So if I have 200 rows, one row's rank may be 3 and another may be 179 (these are arbitrary #'s for example only).
Edit 2
I'm having some luck with this query, but I actually want to avoid ties
SELECT
s.score
, s.created_at
, u.name
, u.location
, u.icon_id
, u.photo
, (SELECT COUNT(*) + 1 FROM scores WHERE score > s.score) AS rank
FROM
scores s
LEFT JOIN
users u ON u.uID = s.user_id
ORDER BY
s.score DESC
, 开发者_开发知识库s.created_at DESC
LIMIT 15
If two or more rows have the same score, I want the latest one (or earliest - I don't care) to be ranked higher. I tried modifying the subquery with AND id > s.id
but that ended up giving me an unexpected result set and different ties.
Select S.score, S.created_at, U.name
, U.location, U.icon_id, U.photo
, (Select Count(*) + 1
From scores S2
Where S2.score > S.score
Or (S2.score = S.Score And S2.created_at > S.created_at)
) AS rank
From scores S
Left Join users U
On U.uID = S.user_id
Order By S.score DESC, S.created_at DESC
LIMIT 15
Of course, if it is possible for two scores to have the same created_at date, then you will still get ties and need to determine a third tie-breaker.
You could order the data in your query.
SELECT user_id, score FROM table ORDER BY score ASC;
This will give you your data from lowest score to highest.
If this doesn't answer your question, then I don't understand what you're asking.
EDIT
To get the position, while iterating through the database results, just keep a counter.
精彩评论