1. 程式人生 > >分組查詢取每組前n條記錄例項

分組查詢取每組前n條記錄例項

假設有這樣一張運動員比賽成績表 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;

查詢結果如下: