1

i want to write a MySQL query to rank scores. If there is a tie between two scores, both should have the same ranking. also after a tie, the next ranking number should be the next consecutive integer value. In other words, there should be no "holes" between ranks.

+----+-------+
| Id | Score |
+----+-------+
| 1  | 3.50  |
| 2  | 3.65  |
| 3  | 4.00  |
| 4  | 3.85  |
| 5  | 4.00  |
| 6  | 3.65  |
+----+-------+

given the above Scores table, the query should generate the following report (order by highest score)

+-------+------+
| Score | Rank |
+-------+------+
| 4.00  | 1    |
| 4.00  | 1    |
| 3.85  | 2    |
| 3.65  | 3    |
| 3.65  | 3    |
| 3.50  | 4    |
+-------+------+

i tried something like the below set @pk1 =''; set @rn1 =1; set @val =1;

SELECT  score,Rank
 FROM
 (
  SELECT  score,
      @rn1 := if(@pk1=score,@rn1, @rn1+@val) as Rank,
      @val := if(@pk1=score,@val+1, 1 ) as value,
      @pk1 := score

  FROM
(SELECT  score FROM scores ORDER BY score) as rank) as scores;

but the above didnt work can anyone help on this

Drew
  • 24,851
  • 10
  • 43
  • 78
sritharan
  • 41
  • 1
  • 10

0 Answers0