本帖最后由 大蓝鲸小蟀锅 于 2018-12-21 14:27 编辑
数据库表初始化:
CREATE TABLE `myscores` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`SName` varchar(11) NOT NULL ,
`ClsNo` varchar(3) NOT NULL ,
`Score` int(3) DEFAULT '0',
PRIMARY KEY (`id`)
); INSERT INTO `myscores` VALUES (1, 'a', 'c1', 78);
INSERT INTO `myscores` VALUES (2, 'b', 'c1', 75);
INSERT INTO `myscores` VALUES (3, 'c', 'c1', 85);
INSERT INTO `myscores` VALUES (4, 'd', 'c1', 82);
INSERT INTO `myscores` VALUES (5, 'e', 'c1', 67);
INSERT INTO `myscores` VALUES (6, 'f', 'c2', 90);
INSERT INTO `myscores` VALUES (7, 'g', 'c2', 84);
INSERT INTO `myscores` VALUES (8, 'h', 'c2', 76);
INSERT INTO `myscores` VALUES (9, 'i', 'c2', 78);
INSERT INTO `myscores` VALUES (10, 'j', 'c2', 71);
INSERT INTO `myscores` VALUES (11, 'k', 'c3', 63);
INSERT INTO `myscores` VALUES (12, 'l', 'c3', 92);
INSERT INTO `myscores` VALUES (13, 'm', 'c3', 80);
INSERT INTO `myscores` VALUES (15, 'n', 'c3', 78);
INSERT INTO `myscores` VALUES (16, 'o', 'c4', 74);
INSERT INTO `myscores` VALUES (17, 'p', 'c4', 83);
INSERT INTO `myscores` VALUES (18, 'q', 'c4', 94);
INSERT INTO `myscores` VALUES (19, 'r', 'c4', 72);
INSERT INTO `myscores` VALUES (20, 's', 'c4', 69);
执行后数据库如图:
MySQL中GROUP BY分组取前N条记录实现mysql分组,取记录
GROUP BY之后如何取每组的前两位下面我来讲述mysql中GROUP BY分组取前N条记录实现方法。
结果:
方法一:
SELECT a.id,a.SName,a.ClsNo,a.Score FROM myscores a
LEFT JOIN myscores b ON a.ClsNo=b.ClsNo AND a.Score<b.Score
GROUP BY a.id,a.SName,a.ClsNo,a.Score having count(b.id)<3
ORDER BY a.ClsNo,a.Score desc;
拆开分析:
LEFT JOIN aa b ON a.ClsNo=b.ClsNo AND a.Score<b.Score
同一个班级(每个班级四个人),分数比当前学生高的记录,那就意味这成绩垫底的学生,将会产生三条记录
GROUP BY a.id,a.SName,a.ClsNo,a.Score having count(b.id)<3
a.id,a.SName,a.ClsNo,a.Score可以代表一个学生(以学生分组),如果count(b.id)<3(成绩超过你的人不能多于3个),那就只剩第一第二了。
方法二:
SELECT * FROM myscores a WHERE (SELECT COUNT(*) FROM myscores WHERE ClsNo=a.ClsNo and Score>a.Score)<3 ORDER BY a.ClsNo,a.Score DESC;
取每一条记录,判断同一个班级,大于当前成绩的同学是不是小于3个人
|