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
相关推荐
sekaii4 分钟前
ReDistribution plan细节
linux·服务器·数据库
焱焱枫40 分钟前
自适应SQL计划管理(Adaptive SQL Plan Management)在Oracle 12c中的应用
数据库·sql·oracle
2301_7930698244 分钟前
Spring Boot +SQL项目优化策略,GraphQL和SQL 区别,Spring JDBC 等原理辨析(万字长文+代码)
java·数据库·spring boot·sql·jdbc·orm
hhw1991121 小时前
spring boot知识点5
java·数据库·spring boot
ITPUB-微风2 小时前
功能开关聚合对象实践:提升金融领域的高可用性
网络·数据库·金融
去看日出2 小时前
Linux(centos)系统安装部署MySQL8.0数据库(GLIBC版本)
linux·数据库·centos
Hanyaoo2 小时前
为什么mvcc中?m_ids 列表并不等同于 min_trx_id 和 max_trx_id 之间的所有事务 ID
数据库
偏右右2 小时前
PL/SQL 异常处理
数据库·sql·oracle
利瑞华3 小时前
Redis 存在线程安全问题吗?为什么?
数据库·redis·安全
小金的学习笔记3 小时前
如何在本地和服务器新建Redis用户和密码
服务器·数据库·redis