mysql5.7 implements the sorting function within the group after grouping ROW_NUMBER() OVER (PARTITION BY)

In versions above mysql 8.0, there is a ROW_NUMBER() OVER (PARTITION BY) function that can be used for grouping and sorting within groups, but versions below 5.7 do not have this function. We can use temporary variables to achieve this effect.

1 group by

Demand example: Now we need to count students' performance rankings in various subjects. We need to install subject subjects to group them, and then sort them in reverse order of scores.
There is a student table as follows:

CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键Id',
  `name` varchar(5) NOT NULL COMMENT '学生姓名',
  `subject` varchar(6) DEFAULT NULL COMMENT '科目',
  `score` smallint(3) DEFAULT NULL COMMENT '分数',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;

The data in the table are as follows:
id name subject score
1 Zhang San Chinese 77
2 Li Si Chinese 67
3 Wang Wu Chinese 85
4 Zhang San Mathematics 82
5 Li Si Mathematics 67
6 Wang Wu English 85
7 Wang Wu Mathematics 85

SELECT a.NAME, a.score, a.SUBJECT, @last :=IF(@FIRST = a.SUBJECT, @last + 1, 1 ) AS rn, @FIRST := a.SUBJEC

Guess you like

Origin blog.csdn.net/web13618542420/article/details/126802806