1 概述
1. 完整格式
(1) row_number() over(partition by 列1 order by 列2)
2. 三种排序函数
(1) row_number(): '连续' 排序,如:1 2 3 4
(2) rank() : '跳跃' 排序,如:1 2 2 4
(3) dense_rank(): '密集' 排序,如:1 2 2 3
3. 分组子句
(1) partition by 列1 order by 列2
(2) order by ... 不可省略(报错提醒)
2 分类
2.1 排序函数
with student_info as (
select 1 sno, '瑶瑶' sname, 18 age from dual union all
select 2 sno, '倩倩' sname, 19 age from dual union all
select 3 sno, '优优' sname, 19 age from dual union all
select 4 sno, '丽丽' sname, 20 age from dual union all
select 5 sno, '萌萌' sname, 21 age from dual
)
select si.sno 学号,
si.sname 姓名,
si.age 年龄,
row_number() over(order by si.age) 连续排序,
rank() over(order by si.age) 跳跃排序,
dense_rank() over(order by si.age) 密集排序
from student_info si;
根据 “年龄 age” 排序的结果:三种排序函数间的区别
2.2 分组子句
with student_info as (
select 1 sno, '瑶瑶' sname, 18 age from dual union all
select 2 sno, '倩倩' sname, 19 age from dual union all
select 3 sno, '优优' sname, 19 age from dual
)
select si.sno 学号,
si.sname 姓名,
si.age 年龄,
row_number() over(partition by si.age order by si.age) rn
from student_info si;
根据 “年龄 age” 分组的结果: