MySQL分组查询获取每个学生前n条分数记录(分组查询前n条记录)
2018-01-11 15:40
726 查看
CREATE TABLE `t_test` ( `id` int(11) NOT NULL AUTO_INCREMENT, `stuid` varchar(36) NOT NULL, `score` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8; INSERT INTO `testdb`.`t_test` (`id`, `stuid`, `score`) VALUES ('1', '111', '90'); INSERT INTO `testdb`.`t_test` (`id`, `stuid`, `score`) VALUES ('2', '111', '11'); INSERT INTO `testdb`.`t_test` (`id`, `stuid`, `score`) VALUES ('3', '111', '34'); INSERT INTO `testdb`.`t_test` (`id`, `stuid`, `score`) VALUES ('4', '111', '99'); INSERT INTO `testdb`.`t_test` (`id`, `stuid`, `score`) VALUES ('5', '222', '11'); INSERT INTO `testdb`.`t_test` (`id`, `stuid`, `score`) VALUES ('6', '222', '33'); INSERT INTO `testdb`.`t_test` (`id`, `stuid`, `score`) VALUES ('7', '222', '41'); INSERT INTO `testdb`.`t_test` (`id`, `stuid`, `score`) VALUES ('8', '333', '123'); INSERT INTO `testdb`.`t_test` (`id`, `stuid`, `score`) VALUES ('9', '333', '100'); INSERT INTO `testdb`.`t_test` (`id`, `stuid`, `score`) VALUES ('10', '333', '99');
测试数据
SELECT *, (SELECT count(id) FROM t_test t2 where t1.stuid=t2.stuid AND t2.score>t1.score -- 获取t2大于t1的记录数 )as maxcnt from t_test t1
到这一步就很简单了.其实只要根据情况取macnt的数据就行了,如果要取前2条,那么筛选maxcnt<2的数据即可.
(如111学生大于99的有0条,大于90的有1条,大于34的有2条,那么要取最高分的前3条,就是maxcnt<3)
SELECT * FROM t_test t1 WHERE ( SELECT count(id) FROM t_test t2 where t2.stuid=t1.stuid and t2.score>t1.score )<3 ORDER BY stuid asc,score DESC
效果图
相关文章推荐
- mysql分组查询获取组内某字段最大的记录
- Mysql相关子查询&&MySQL获取分组后的TOP N记录
- mysql查询获取分组后最新的一条记录,策略:先排序,然后在次分组查询(默认第一条),就是最新的一条数据了
- [MySQL]学习笔记- 用户行为表中,查询每个人的一条最新行为(分组 排序 取时间最大的一条记录)
- oracle或mysql分组查询并且获取前3条排序后的数据
- 获取MySQL的表中每个userid最后一条记录的方法
- MySQL 查询分页数据中分组后取每组的前N条记录
- 如何在mysql中查询每个分组的前几名
- 获取分组后取某字段最大一条记录(求每个类别中最大的值的列表)
- MySQL获取分组后的TOP 1和TOP N记录-转
- mysql按字段分组并获取每个分组按照某个字段排序的前三条
- mysql分组查询取分组后各分组中的最新一条记录
- 记录一个mysql按日期分组统计的查询
- mysql连接查询-主从表连接查询:获取从表最新一条表记录;获取没有从表记录的主表信息
- [MS SQL]SQL语句查询每个分组的前N条记录的实现方法
- MySQL查询分页,同时获取总记录数
- SQL语句查询每个分组的前N条记录的实现方法
- MySQL——关于MySQL分组查询group by和order by获取最新时间内容的方法
- MySQL获取分组后的TOP 1和TOP N记录