mysql 中数据分组排序取前n条数据

文章展示了如何在MySQL中使用ROW_NUMBER()窗口函数,按班级分组并对每个班级的学生分数进行降序排序,然后选取每个班级分数最高的n条记录。示例包括创建和填充`stuscore`表,以及逐步查询过程,最终获取每个班级前3名学生的详细信息。
摘要由CSDN通过智能技术生成

mysql 中数据分组排序取前n条数据

1 sql语句

CREATE TABLE `stuscore`  (
  `userId` int(11) NOT NULL COMMENT '学生ID',
  `classId` int(11) NOT NULL COMMENT '班级',
  `score` int(255) NULL DEFAULT NULL COMMENT '得分',
  PRIMARY KEY (`userId`) USING BTREE
)  ;
 
-- ----------------------------
-- Records of stuscore
-- ----------------------------
INSERT INTO `stuscore` VALUES (101, 1, 100);
INSERT INTO `stuscore` VALUES (102, 2, 298);
INSERT INTO `stuscore` VALUES (103, 3, 105);
INSERT INTO `stuscore` VALUES (104, 1, 49);
INSERT INTO `stuscore` VALUES (105, 3, 200);
INSERT INTO `stuscore` VALUES (106, 2, 39);
INSERT INTO `stuscore` VALUES (107, 1, 300);
INSERT INTO `stuscore` VALUES (108, 2, 140);
INSERT INTO `stuscore` VALUES (109, 3, 168);
INSERT INTO `stuscore` VALUES (110, 3, 28);
INSERT INTO `stuscore` VALUES (111, 2, 234);
INSERT INTO `stuscore` VALUES (112, 1, 270);
INSERT INTO `stuscore` VALUES (113, 1, 345);
INSERT INTO `stuscore` VALUES (114, 2, 31);
INSERT INTO `stuscore` VALUES (115, 3, 242);
INSERT INTO `stuscore` VALUES (116, 3, 120);

2 按班级分组,取分数最高的n个人

– 需求:按班级分组,取分数最高的n个人
– ROW_NUMBER () over (partition by classId order by score desc)
– 按照班级分组,按照分数降序

2.1 按班级分组,排序

--step1 按班级分组,排序 
 select
      t.classId,
      t.userId,
      t.score,
      ROW_NUMBER () over (partition by classId order by score desc) rn
 from stuscore t

-- 查询结果
classId userId  score  rn
1		113		345		1
1		107		300		2
1		112		270		3
1		101		100		4
1		104		49		5
2		102		298		1
2		111		234		2
2		108		140		3
2		106		39		4
2		114		31		5
3		115		242		1
3		105		200		2
3		109		168		3
3		116		120		4
3		103		105		5
3		110		28		6


2.2 查询前3条

select 
  classId,
  userId,
  score
from (
 select
      t.classId,
      t.userId,
      t.score,
      ROW_NUMBER () over (partition by classId order by score desc) rn
 from stuscore t
 ) a 
where a.rn <= 3;-- 前三条 <= 3

-- 查询结果
classId	userId	score
1		113		345
1		107		300
1		112		270
2		102		298
2		111		234
2		108		140
3		115		242
3		105		200
3		109		168
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值