MySQL分组,并获取分组的前几条记录
创建表t1
mysql> show create table t1\G
*************************** 1. row ***************************
Table: t1
Create Table: CREATE TABLE `t1` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`std` int(11) DEFAULT NULL,
`std_name` varchar(20) DEFAULT NULL,
`kecheng` varchar(20) DEFAULT NULL,
`score` decimal(5,2) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4
1 row in set (0.00 sec)
插入数据
mysql> insert into t1 values (1,1,'aa','yuwen',99.9),(2,1,'aa','shuxue',90.1),(3,1,'aa','yingyu',88.8);
mysql> insert into t1 values (4,2,'bb','yuwen',94.9),(5,2,'bb','shuxue',98.1),(6,2,'bb','yingyu',98.8);
mysql> insert into t1 values (9,3,'cc','yuwen',64.9),(8,3,'cc','shuxue',93.1),(7,3,'cc','yingyu',78.8);
获取std分组的前2条记录
mysql> select * from t1 a where (select count(*) from t1 b where a.std=b.std and a.score<=b.score)<=2 ;
+----+------+----------+---------+--------+
| id | std | std_name | kecheng | score |
+----+------+----------+---------+--------+
| 1 | 1 | aa | yuwen | 100.00 |
| 2 | 1 | aa | shuxue | 90.00 |
| 5 | 2 | bb | shuxue | 98.10 |
| 6 | 2 | bb | yingyu | 98.80 |
| 7 | 3 | cc | yingyu | 78.80 |
| 8 | 3 | cc | shuxue | 93.10 |
+----+------+----------+---------+--------+
6 rows in set (0.00 sec)
本文详细介绍如何在MySQL中使用自定义SQL语句实现分组并获取每组排名前几的记录,通过具体实例展示了如何根据学生姓名和课程成绩进行分组及排名,适用于需要进行数据分组和排名的场景。
2952

被折叠的 条评论
为什么被折叠?



