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
相关推荐
北邮刘老师1 天前
从软件工程(SE)到智能体工程(AE):开发范式的差异与升级
数据库·人工智能·架构·软件工程·智能体·智能体互联网
Predestination王瀞潞1 天前
Java EE数据访问框架技术(第二章:Mybatis多表关系映射)
数据库
+VX:Fegn08951 天前
计算机毕业设计|基于springboot + vue酒店预约系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
wheeldown1 天前
数据库复习自用
数据库·sql·oracle
程序猿20231 天前
MySQL的锁-全局锁及表锁
数据库·mysql
ss2731 天前
线程安全三剑客:无状态、加锁与CAS
java·jvm·数据库
m0_598177231 天前
MYSQL(进阶--1)--
数据库·mysql
打不了嗝 ᥬ᭄1 天前
【MySQL】索引和事务
数据库·mysql
北邮刘老师1 天前
【智能体互联协议解析】智能体点对点交互模式的三种实现方式和应用场景
数据库·人工智能·架构·智能体·智能体互联网
豆浆Whisky1 天前
6小时从0到1:我用AI造了个分片SQL生成器
后端·sql·ai编程