日期:2014-05-16  浏览次数:20714 次

使用分析函数来为记录排名的问题
[size=large]现在有三个表student,score,course
对应的建表语句如下:
CREATE TABLE student(
student_id NUMBER PRIMARY KEY,
student_name,VARCHAR2(30) NOT NULL)

CREATE TABLE score(
score_id NUMBER PRIMARY KEY,
student_id NUMBER,
course_id NUMBER,
score NUMBER)

CREATE TABLE course(
course_id NUMBER PRIMARY KEY,
course_name VARCHAR2(30))

要求用基本SQL实现如下的两条查询要求:
(1) 求出每门课程成绩排名前五名的同学的姓名,分数和课程名
(2)求出每门课程成绩排名第三的同学的姓名,分数和课程名

Oracle的解法:
表及数据:

Sql代码
<SPAN style="FONT-SIZE: large">create table STUDENT  
(  
  STUDENT_ID   NUMBER not null,  
  STUDENT_NAME VARCHAR2(30) not null 
)  
;  
alter table STUDENT  
  add primary key (STUDENT_ID);  
 
prompt Loading STUDENT...  
insert into STUDENT (STUDENT_ID, STUDENT_NAME)  
values (1, '张三');  
insert into STUDENT (STUDENT_ID, STUDENT_NAME)  
values (2, '李四');  
insert into STUDENT (STUDENT_ID, STUDENT_NAME)  
values (3, '王五');  
insert into STUDENT (STUDENT_ID, STUDENT_NAME)  
values (4, '马六');  
insert into STUDENT (STUDENT_ID, STUDENT_NAME)  
values (5, '孙七');  
insert into STUDENT (STUDENT_ID, STUDENT_NAME)  
values (6, '王八');  
commit;</SPAN> 

create table STUDENT
(
  STUDENT_ID   NUMBER not null,
  STUDENT_NAME VARCHAR2(30) not null
)
;
alter table STUDENT
  add primary key (STUDENT_ID);

prompt Loading STUDENT...
insert into STUDENT (STUDENT_ID, STUDENT_NAME)
values (1, '张三');
insert into STUDENT (STUDENT_ID, STUDENT_NAME)
values (2, '李四');
insert into STUDENT (STUDENT_ID, STUDENT_NAME)
values (3, '王五');
insert into STUDENT (STUDENT_ID, STUDENT_NAME)
values (4, '马六');
insert into STUDENT (STUDENT_ID, STUDENT_NAME)
values (5, '孙七');
insert into STUDENT (STUDENT_ID, STUDENT_NAME)
values (6, '王八');
commit;  Sql代码
<SPAN style="FONT-SIZE: large">create table COURSE  
(  
  COURSE_ID   NUMBER not null,  
  COURSE_NAME VARCHAR2(30)  
)  
;  
alter table COURSE  
  add primary key (COURSE_ID);  
 
prompt Loading COURSE...  
insert into COURSE (COURSE_ID, COURSE_NAME)  
values (1, '语文');  
insert into COURSE (COURSE_ID, COURSE_NAME)  
values (2, '数学');  
insert into COURSE (COURSE_ID, COURSE_NAME)  
values (3, '英语');  
commit;</SPAN> 

create table COURSE
(
  COURSE_ID   NUMBER not null,
  COURSE_NAME VARCHAR2(30)
)
;
alter table COURSE
  add primary key (COURSE_ID);

prompt Loading COURSE...
insert into COURSE (COURSE_ID, COURSE_NAME)
values (1, '语文');
insert into COURSE (COURSE_ID, COURSE_NAME)
values (2, '数学');
insert into COURSE (COURSE_ID, COURSE_NAME)
values (3, '英语');
commit;  Sql代码
<SPAN style="FONT-SIZE: large">create table SCORE  
(  
  SCORE_ID   NUMBER not null,  
  STUDENT_ID NUMBER,  
  COURSE_ID  NUMBER,  
  SCORE      NUMBER  
)  
;  
alter table SCORE