SQL面试题挑战13:分组topN

目录

问题:

下面是某个班级的成绩表,需要筛选出每个科目前2名的学生信息。如果分数一样,名次是并列的,后面的同学名次就不连续。比如有2个同学是第一名,那么下一个同学的名次就是第3名,呈现1,1,3的名次排列。

powershell 复制代码
stu_id  stu_name    subject     score
1001    张三        语文           90
1001    张三        数学           80
1001    张三        英语           70
1002    李四        语文           90
1002    李四        数学           75
1002    李四        英语           80
1003    王五        语文           80
1003    王五        数学           70
1003    王五        英语           60

SQL解答:

非常典型的分组topN的问题,是面试经常被问到的。直接使用开窗函数排名即可,注意下row_number、rank、dense_rank三个开窗函数不同场景下的使用。

sql 复制代码
with temp as
(
    select 1001 as stu_id,'张三' as stu_name,'语文' as subject,90 as score
    union all
    select 1001 as stu_id,'张三' as stu_name,'数学' as subject,80 as score
    union all
    select 1001 as stu_id,'张三' as stu_name,'英语' as subject,70 as score
    union all
    select 1002 as stu_id,'李四' as stu_name,'语文' as subject,90 as score
    union all
    select 1002 as stu_id,'李四' as stu_name,'数学' as subject,75 as score
    union all
    select 1002 as stu_id,'李四' as stu_name,'英语' as subject,80 as score
    union all
    select 1003 as stu_id,'王五' as stu_name,'语文' as subject,80 as score
    union all
    select 1003 as stu_id,'王五' as stu_name,'数学' as subject,70 as score
    union all
    select 1003 as stu_id,'王五' as stu_name,'英语' as subject,60 as score
)
select
stu_id
,stu_name
,subject
,score
from
(
   select 
    stu_id
    ,stu_name
    ,subject
    ,score
    ,rank() over(partition by subject order by score desc) as rk
    from temp
) t1
where rk<=2;

---结果:
stu_id		stu_name		subject			score	
1001          张三            数学           80	
1002          李四            数学           75
1002          李四            英语           80	
1001          张三            英语           70	
1001          张三            语文           90
1002          李四            语文           90
相关推荐
Alt.931 分钟前
MyBatis基础五(动态SQL,缓存)
java·sql·mybatis
@淡 定42 分钟前
MySQL MVCC 机制解析
数据库·mysql
Chandler2442 分钟前
Redis:内存淘汰原则,缓存击穿,缓存穿透,缓存雪崩
数据库·redis·缓存
SRC_BLUE_171 小时前
Python GUI 编程 | QObject 控件基类详解 — 定时器
开发语言·数据库·python
DBWYX1 小时前
MySQL 进阶 面经级
数据库·mysql
喝醉酒的小白2 小时前
SQL Server:触发器
数据库
银河金融数据库3 小时前
历史分钟高频数据
数据库·金融
男Ren、麦根3 小时前
MySQL 复制与主从架构(Master-Slave)
数据库·mysql·架构
viperrrrrrrrrr74 小时前
大数据学习(95)-谓词下推
大数据·sql·学习
嘉友5 小时前
Redis zset数据结构以及时间复杂度总结(源码)
数据结构·数据库·redis·后端