oracle:进行分组并取每组中的前n条记录

关键字: oracle 分组 前n条记录

题目:

在oracle中有一数据表exam_result(成绩记录表),

表中的一条记录描述了“某个班某个学生某次考试的成绩"

create table EXAM_RESULT 

  ID      NUMBER(10) not null,                   --主键
  CLASSID NUMBER(10) not null,           --  班级id,关联到班级表
  USERID  NUMBER(10) not null,             --用户id,关联到用户表
  EXAMID  NUMBER(10) not null,             --试卷id,关联到试卷表
  RESULT  NUMBER(3)                              --成绩
)

 

现在要求统计完成了试卷id为1,2,3的成绩的前3名

即完成了试卷id为1的前3名,完成了试卷id为2的前3名,完成了试卷id为3的前3名

 

Sql代码 
  1. select * from (  
  2.       select   
  3.         e.classid,   
  4.         e.userid,   
  5.         e.examid,   
  6.         e.result,   
  7.             row_number() over (partition by e.examid order by e.examid, e.result desc) rn  
  8.                 from exam_result e   
  9.                         where e.examid in (1,2,3)  
  10. where rn <= 3  
 
posted @ 2010-04-07 15:42  好俊的功夫啊  阅读(3861)  评论(1编辑  收藏  举报