表scores (name,sex,score),分别获取男女前三名学生姓名。
建立表格:
create table scores (
name varchar2(8),sex varchar2(1),score number(3,0)
)
插入学生成绩
insert into scores(name,sex,score) values (‘男A‘,‘1‘,100);
insert into scores(name,sex,score) values (‘男B‘,‘1‘,90);
insert into scores(name,sex,score) values (‘男C‘,‘1‘,80);
insert into scores(name,sex,score) values (‘男D‘,‘1‘,70);
insert into scores(name,sex,score) values (‘女A‘,‘2‘,100);
insert into scores(name,sex,score) values (‘女B‘,‘2‘,90);
insert into scores(name,sex,score) values (‘女C‘,‘2‘,80);
insert into scores(name,sex,score) values (‘女D‘,‘2‘,70);
查询:
SELECT name, sex,score
FROM (SELECT name,
sex,
score,
ROW_NUMBER() OVER(PARTITION BY sex ORDER BY score DESC) RW
FROM scores)
WHERE RW < 4
运行结果:
1 男A 1 100
2 男B 1 90
3 男C 1 80
4 女A 2 100
5 女B 2 90
6 女C 2 80