这里,简单学习下row_number这个函数
函数基本语法
row_number() over(partition by xx order by xx asc/desc)
准备:
create table y_person(
id number,
group_id number,
name varchar2(50)
);
insert into y_person(id,group_id,name)
select 1011,101,'李白' from dual
union select 1012,101,'杜甫' from dual
union select 1021,102,'白居易' from dual
union select 1031,103,'宋江' from dual
union select 1032,103,'李奎' from dual
union select 1032,103,'李奎' from dual
union select 1033,103,'武松' from dual
union select 1041,104,'路飞' from dual;
1. row_number() over(order by xx)
只使用order by,会让数据按照xx进行排序,如:
select
id,
group_id,
name ,
row_number() over(order by id ) p_order
from y_person
这里的结果集,按照id进行排序,并分配序号,这里的序号是连续的,比如,我们再根据group_id进行排序
,即使有相同的group_id,排序也是连续的
2. row_number() over(partition by xx order by xx )
这里,会先根据partition by进行分组,然后在组内进行排名,显示序号,如:
select
id,
group_id,
name ,
row_number() over(partition by group_id order by id ) p_order
from y_person
我们根据group_id,进行分组后,会再根据id进行排序,然后分配一个序号