---
title: "oracle:进行分组并取每组中的前n条记录"
author: "lingshangwen"
date: "2009-05-19T22:56:11Z"
tags: []
slug: "oracle-n"
draft: false
lastmod: "2009-05-19T22:56:11Z"
id: 391481
url: "https://eagle516.iteye.com/blog/391481"
---

题目:

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