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
相关推荐
时序数据说4 分钟前
时序数据库IoTDB在航空航天领域的解决方案
大数据·数据库·时序数据库·iotdb
.生产的驴18 分钟前
SpringBoot 封装统一API返回格式对象 标准化开发 请求封装 统一格式处理
java·数据库·spring boot·后端·spring·eclipse·maven
AnsenZhu30 分钟前
2025年Redis分片存储性能优化指南
数据库·redis·性能优化·分片
oydcm1 小时前
MySQL数据库概述
数据库·mysql
oioihoii1 小时前
C++23中if consteval / if not consteval (P1938R3) 详解
java·数据库·c++23
带娃的IT创业者1 小时前
《AI大模型趣味实战》基于RAG向量数据库的知识库AI问答助手设计与实现
数据库·人工智能
husterlichf2 小时前
MYSQL 常用数值函数 和 条件函数 详解
数据库·sql·mysql
我的golang之路果然有问题2 小时前
快速了解redis,个人笔记
数据库·经验分享·redis·笔记·学习·缓存·内存
卡皮巴拉爱吃小蛋糕3 小时前
MySQL的MVCC【学习笔记】
数据库·笔记·mysql
农民也会写代码3 小时前
dedecms织梦arclist标签noflag属性过滤多个参数
开发语言·数据库·sql·php·dedecms