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

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

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

1、

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

 

2、

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


3、

 

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


查询结果如下:

 

posted @ 2017-01-05 10:45  QQ天堂  阅读(262)  评论(0编辑  收藏  举报