ITeye博客

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

lingshangwen · 2009-05-19 22:56 · 编程 · Markdown

题目:

在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名

 

select * from (
      select 
		e.classid, 
		e.userid, 
		e.examid, 
		e.result, 
        	row_number() over (partition by e.examid order by e.examid, e.result desc) rn
       			from exam_result e 
				        where e.examid in (1,2,3)
) where rn <= 3

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。