1.如下图,有两个班,分别是四个人,每个班都有2名学渣,2个学霸
2.利用row_number() 函数 对两个班级进行排名,如下图
3.查出每个班级前三名的同学,正好利用上图的rank,观察到上图的rank 就是每个人在自己班级的名次,所以在外面包裹一层 在条件查询就可以了
附上sql语句:
WITH cte AS (SELECT ‘一班‘ 班级, ‘张三‘ 姓名, 12 成绩 UNION ALL SELECT ‘一班‘ 班级, ‘张四‘ 姓名, 24 成绩 UNION ALL SELECT ‘二班‘ 班级, ‘张五‘ 姓, 38 成绩 UNION ALL SELECT ‘二班‘ 班级, ‘张六‘ 姓名, 98 成绩 UNION ALL SELECT ‘二班‘ 班级, ‘张七‘ 姓名, 45 成绩 UNION ALL SELECT ‘一班‘ 班级, ‘张八‘ 姓名, 87 成绩 UNION ALL SELECT ‘二班‘ 班级, ‘张九‘ 姓名, 95 成绩 UNION ALL SELECT ‘一班‘ 班级, ‘张十‘ 姓名, 88 成绩) --SELECT * FROM cte order by [班级] desc select a.* from ( select row_number() over(PARTITION by [班级] order by [成绩] desc ) rank,* from cte ) a where a.rank<=3 order by 班级 desc,rank asc
时间: 2024-10-09 14:33:39