惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Apple Machine Learning Research
Apple Machine Learning Research
Y
Y Combinator Blog
博客园 - 【当耐特】
V
Visual Studio Blog
GbyAI
GbyAI
V
V2EX
P
Proofpoint News Feed
Microsoft Azure Blog
Microsoft Azure Blog
Microsoft Security Blog
Microsoft Security Blog
D
DataBreaches.Net
Hugging Face - Blog
Hugging Face - Blog
A
About on SuperTechFans
The Cloudflare Blog
阮一峰的网络日志
阮一峰的网络日志
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
N
Netflix TechBlog - Medium
aimingoo的专栏
aimingoo的专栏
B
Blog RSS Feed
量子位
MongoDB | Blog
MongoDB | Blog
有赞技术团队
有赞技术团队
人人都是产品经理
人人都是产品经理
Stack Overflow Blog
Stack Overflow Blog
小众软件
小众软件

博客园 - o岸上的鱼o

ArrayList的使用方法【转载】 ORACLE与SQL SERVER的区别 什么是.do文件? Dell HP服务器命名规则 【转】OS6.1.2完美越狱 ORACLE EXP/IMP 说明 . 【转】oracle导入导出命令详解 . plsql函数大全 oracle中的SGA和PGA 常用会计科目通俗解释 SAP IDES、DEV、QAS、PRD都是什么含义/SAP实施方法分几步【转】 什么叫SAP-IDES EAM概述(什么是EAM?) 什么是EAM?定义、原理、核心 . 常见时间管理工具 迭代与增量的共性与区别 oracle pl/sql 中创建同义词 oracle pl/sql 基础 Excel 作复合饼图和双轴柱形图
随笔 - 191, 文章 - 0, 评论 - 97, 阅读 - 104万 用SQL查询方...
o岸上的鱼o · 2022-05-12 · via 博客园 - o岸上的鱼o

用SQL查询方式显示GROUP BY中的TOP
怎样用一个SQL语句来显示
分组后每个组的前几位
比如把一个学校所有学生的成绩按班级分组,再显示每个班级前五名的信息。
班级     学生   成绩
一班     李X       100
一班     王X       99
一班     刘X       98
一班     赵X       97
一班     孙X       96
二班     李W       100
二班     王W       99
二班     刘W       98
二班     赵W       97
二班     孙W       96
......

------解决方案--------------------
declare @t table (class varchar(20),name varchar(10),grade int)
insert @t select '一班 ', '李X ',100
union all select '一班 ', '王X ',99
union all select '一班 ', '刘X ',98
union all select '一班 ', '赵X ',97
union all select '一班 ', '孙X ',96
union all select '一班 ', '孙X ',78
union all select '二班 ', '李W ',100
union all select '二班 ', '王W ',99
union all select '二班 ', '刘W ',98
union all select '二班 ', '赵W ',97
union all select '二班 ', '孙W ',96
union all select '二班 ', '孙X ',88

select * from @t a where
(select count(1) from @t where class="a".class and grade> a.grade) <5
order by class,grade desc
--结果
class name grade
-------------------- ---------- -----------
二班 李W 100
二班 王W 99
二班 刘W 98
二班 赵W 97
二班 孙W 96
一班 李X 100
一班 王X 99
一班 刘X 98
一班 赵X 97
一班 孙X 96

(所影响的行数为 10 行)

原文地址:http://www.myexception.cn/sql-server/158915.html