分组查询取每组前n条记录实例

本文介绍如何使用SQL查询语句来筛选出每个国家的前三名比赛成绩记录,包括两种实现方式及其查询结果展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

假设有这样一张运动员比赛成绩表 tb_score


现在要求查询出每个国家的前三名的成绩记录,查询语句可以这样写:

1、

select t3.id,t3.country,t3.score 
from (select t1.*, (select count(*) from tb_score t2 where t1.score<=t2.score and t1.country=t2.country) as rownum 
			from tb_score t1) t3 
where rownum <=3 order by country,score DESC;


2、

select a.id,a.country,a.name,a.score from tb_score a 
where exists 
(select count(*) from tb_score where country = a.country and score > a.score having Count(*) < 3)
order by a.country,score DESC;

3、

select a.id,a.country,a.name,a.score from tb_score a 
where 
(select count(*) from tb_score where country = a.country and score > a.score )<3
order by a.country,score DESC;

查询结果如下:







评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值