对分数进行排名,排名必须连续

需求:对分数进行排名,排名必须连续

CREATE TABLE `stu` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT '' COMMENT '学生名',
  `class` int(11) DEFAULT NULL COMMENT '班级',
  `score` int(11) DEFAULT NULL COMMENT '分数',
  PRIMARY KEY (`ID`),
  UNIQUE KEY `unique_idx_name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COMMENT='学生';

INSERT INTO `mytest`.`stu` (`ID`, `name`, `class`, `score`) VALUES ('1', 'a', '1', '88');
INSERT INTO `mytest`.`stu` (`ID`, `name`, `class`, `score`) VALUES ('2', 'b', '1', '99');
INSERT INTO `mytest`.`stu` (`ID`, `name`, `class`, `score`) VALUES ('3', 'c', '2', '99');
INSERT INTO `mytest`.`stu` (`ID`, `name`, `class`, `score`) VALUES ('4', 'd', '2', '97');
INSERT INTO `mytest`.`stu` (`ID`, `name`, `class`, `score`) VALUES ('5', 'e', '2', '97');
INSERT INTO `mytest`.`stu` (`ID`, `name`, `class`, `score`) VALUES ('6', 'f', '2', '98');
INSERT INTO `mytest`.`stu` (`ID`, `name`, `class`, `score`) VALUES ('7', 'g', '2', '55');
 

SELECT
    Score,
    (
        SELECT
            count(DISTINCT score)
        FROM
            stu
        WHERE
            score >= s.score
    ) AS Rank
FROM
    stu s
ORDER BY
    Score DESC;

Score    Rank
99    1
99    1
98    2
97    3
97    3
88    4
55    5

你可能感兴趣的:(算法)