假设表格为student, 数据如下:
student数据
我们要在MySQL中实现Oracle中的rank()函数功能,即组内排序,具体来说: 就是对student表中按照课程(course)对学生(name)按分数(score)高低进行排名。
首先新建存储过程realize_rank_in_MySQL,代码如下:
DROP PROCEDURE IF EXISTS realize_rank_in_MySQL; DELIMITER ;; CREATE PROCEDURE realize_rank_in_MySQL() BEGIN DECLARE i int; SET i = 0; WHILE i < (select count(DISTINCT course) from student) DO SET @ROW =0; INSERT INTO student_rank SELECT *, (@ROW:=@ROW+1) AS rank FROM student WHERE course=(select DISTINCT course from student limit i,1) ORDER BY score DESC; set i = i + 1; END WHILE; END ;; DELIMITER ;
然后输入以下查询语句即可:
drop table if exists student_rank; create table student_rank like student; alter table student_rank add rank int; call realize_rank_in_MySQL; select * from student_rank;
结果如下:
注意:这里的排名并没有实现分数相同时排名也一样的情形。
作者:但盼风雨来_jc
链接:https://www.jianshu.com/p/a1e651fe774d