今天有同事说到了怎么MySQL中查询获取每个班级成绩前三名的学生信息,在网上查了查,然后写出代码,很快就OK了。
CREATE TABLE t_testscore( pk_id INT PRIMARY KEY, c_name VARCHAR(50) , c_score INT, c_class INT )DEFAULT CHARSET=utf8;
INSERT INTO t_testscore VALUES (1, ‘张三6‘, 66, 1),(2, ‘张三5‘, 65, 1),(3, ‘张三4‘, 64, 1), (4, ‘张三3‘, 63, 1),(5, ‘张三2‘, 62, 1);
INSERT INTO t_testscore VALUES (11, ‘李四6‘, 76, 2),(12, ‘李四5‘, 75, 2),(13, ‘李四4‘, 74, 2), (14, ‘李四3‘, 73, 2),(15, ‘李四2‘, 72, 2);
SELECT * FROM t_testscore t
WHERE EXISTS(SELECT COUNT(*) FROM t_testscore ts WHERE ts.c_score>=t.c_score GROUP BY ts.c_class HAVING COUNT(*)<=3)
ORDER BY c_class,c_score DESC;
时间: 2024-10-26 15:26:46