How to rank a record with same weight in MySQL

孤街醉人 提交于 2019-12-12 04:22:15

问题


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.


回答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




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/39214022/how-to-rank-a-record-with-same-weight-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!