How do I Handle Ties When Ranking Results in MySQL?

Posted by Laxmidi on Stack Overflow See other posts from Stack Overflow or by Laxmidi
Published on 2010-03-19T01:05:39Z Indexed on 2010/03/19 1:11 UTC
Read the original article Hit count: 427

Filed under:
|

Hi,

How does one handle ties when ranking results in a mysql query? I've simplified the table names and columns in this example, but it should illustrate my problem:

SET @rank=0;
SELECT student_names.students, @rank := @rank +1 AS rank, scores.grades
FROM student_names  
LEFT JOIN scores ON student_names.students = scores.students
ORDER BY scores.grades DESC

So imagine the the above query produces:

Students  Rank  Grades
Al         1     90
Amy        2     90
George     3     78
Bob        4     73
Mary       5     NULL
William    6     NULL

Even though Al and Amy have the same grade, one is ranked higher than the other. Amy got ripped-off. How can I make it so that Amy and Al have the same ranking, so that they both have a rank of 1. Also, William and Mary didn't take the test. They bagged class and were smoking in the boy's room. They should be tied for last place.

The correct ranking should be:

Students  Rank  Grades
Al         1     90
Amy        1     90
George     3     78
Bob        4     73
Mary       5     NULL
William    5     NULL

If anyone has any advice, please let me know.

Thank you!

-Laxmidi

© Stack Overflow or respective owner

Related posts about mysql

Related posts about rank