0

Suppose I have a data say:

  Name   | Marks   
StudentA | 90
StudentB | 85
StudentC | 85
StudentD | 70

now StudentA will get 1st Rank, StudentB and StudentC will get 2nd Rank and Student D will get 4th Rank.

I know the basic rank computation if there are no duplicate weights, but how to handle if we encounter 2 similar weights as in this case there are two 85 marks which will share rank 2.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80

3 Answers3

1

In php you can implement it in the following way:

$data = [
    [95, 0], [85, 0], [85, 0], [85, 0], [70, 0], [70, 0], [50, 0]
];

$rank = 0;
$previous = null;
$skippedRank = 0;
foreach ($data as &$item) {
    if ($item[0] != $previous) {
        $rank += $skippedRank+1;
        $previous = $item[0];
        $skippedRank = 0;
    } else {
        $skippedRank++;
    }

    $item[1] = $rank;
}

print_r($data);

where $item[0] is weight and $item[1] is rank.

Andrej
  • 7,474
  • 1
  • 19
  • 21
1

You can use an additional variable to hold the mark of the previous record:

SELECT Name, Marks,
       @rnk := IF(@prevMark = Marks, @rnk,
                  IF(@prevMark := Marks, @rnk + 1, @rnk + 1)) AS rank                
FROM mytable
CROSS JOIN (SELECT @rnk := 0, @prevMark := 0) AS vars
ORDER BY Marks DESC

Demo here

Strawberry
  • 33,750
  • 13
  • 40
  • 57
Giorgos Betsos
  • 71,379
  • 9
  • 63
  • 98
1

Using Giorgos's fiddle...

SELECT name
     , marks
     , FIND_IN_SET(marks, (SELECT GROUP_CONCAT(marks ORDER BY marks DESC) FROM mytable)) rank
  FROM mytable;

|     Name | Marks | rank |
|----------|-------|------|
| StudentA |    90 |    1 |
| StudentB |    85 |    2 |
| StudentC |    85 |    2 |
| StudentD |    70 |    4 |

http://sqlfiddle.com/#!9/7cc30/6

or

SELECT name, marks, rank
FROM (SELECT name
     , marks
     , @prev := @curr
     , @curr := marks
     , @i:=@i+1 temp
     , @rank := IF(@prev = @curr, @rank, @i) AS rank
  FROM mytable
     , ( SELECT @curr := null, @prev := null, @rank := 0, @i:=0) vars
 ORDER 
    BY marks DESC,name
      ) x
      ORDER 
    BY marks DESC,name

http://sqlfiddle.com/#!9/287e07/9

Strawberry
  • 33,750
  • 13
  • 40
  • 57