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
相关推荐
Mr.朱鹏7 小时前
Linux 服务器 LVM 根分区在线动态扩容
linux·服务器·数据库
摇滚侠7 小时前
《SpringBoot 3:入门与应用实战》第 12 章 JDBC 与事务 数据库初始化机制 阅读笔记 36
数据库·spring boot·笔记
qiuhaipeng17 小时前
Claude code 升级后上下文长度变短问题
java·前端·数据库
wxwx_bscxy3228 小时前
基于Python新冠疫情可视化分析系统的设计与实现
java·数据库·spring boot·python·微信小程序·sqlite
剑之所向9 小时前
.NET 官方`System.Threading.Channels`
前端·javascript·数据库
词却9 小时前
数据库基础:DQL 数据查询语言
数据库·oracle
昌原的儿子LEO11 小时前
Linux IO多路复用与SQLite数据库核心知识点总结
linux·数据库·oracle
山岚的运维笔记11 小时前
mysql 专业笔记 -- 第 8 章:使用变量
运维·数据库·笔记·后端·学习·mysql·dba
聚美智数12 小时前
网安查询-备案查询-网络安全查询API接口介绍
网络·数据库·web安全
坐吃山猪12 小时前
【多线程】Semaphore使用
java·数据库·oracle·多线程