Oracle高级查询之over(partition by...)
现有表,数据如下:
eg1:查询年龄第二的队员
通常写法:
select * from (select a.*, rownum r from (select t.* from l_student_info_tbl t order by t.sage desc) a) b where b.r = 2
看下a子句结果集:
但如果时要统计每个年级,年龄第二大的,上面的sql就不行了,子句必须指定具体年级才可以按年级排序。
rank()/dense_rank() over(partition by ...order by ...)
现在导入一批东吴势力。
select e.* from (select e.*, rank() over(partition by e.sclassno order by e.sage desc) rank from l_student_info_tbl e) e where e.rank = 2;
结果:
over: 在什么条件之上。
partition by e.sclassno: 按年级编号划分(分区)。
order by e.sage desc: 按年龄从高到低排序(使用rank()/dense_rank() 时,必须要带order by否则非法)
rank()/dense_rank(): 分级
rank(): 跳跃排序,如果有两个第一级时,接下来就是第三级。
dense_rank(): 连续排序,如果有两个第一级时,接下来仍然是第二级
select e.* from (select e.*, dense_rank() over(partition by e.sclassno order by e.sage desc) rank from l_student_info_tbl e) e where e.rank = 4;
select e.* from (select e.*, rank() over(partition by e.sclassno order by e.sage desc) rank from l_student_info_tbl e) e where e.rank = 4;
看下子句,无rank=4的数据