排序函数row_number,rank,dense_rank区别

row_number,rank,dense_rank这三个都是排序函数,几乎每种数据库都支持这几个函数。
它们都是配合开窗函数over(partition by col1 order by col2)使用。下面根据实例看看这三个有什么区别:

首先建个临时表,然后插入一些数据:

create table tmp_user(
a varchar2(6),
b int);


insert into tmp_user(a,b) 
select 'A',10 from dual union all
select 'A',20 from dual union all
select 'A',20 from dual union all
select 'A',30 from dual union all
select 'A',40 from dual union all
select 'A',50 from dual union all
select 'B',10 from dual union all
select 'B',20 from dual union all
select 'B',20 from dual union all
select 'B',30 from dual union all
select 'B',30 from dual union all
select 'B',60 from dual;

然后执行查询语句:

select a,
       b,
       rank() over(partition by a order by b desc) rank,
       dense_rank() over(partition by a order by b desc) dense_rank,
       row_number() over(partition by a order by b desc) row_number
  from tmp_user;

结果为:

RN	A	B	RANK DENSE_RANK ROW_NUMBER
1	A	50	1	1	1
2	A	40	2	2	2
3	A	30	3	3	3
4	A	20	4	4	4    <------
5	A	20	4	4	5    <------
6	A	10	6	5	6
7	B	60	1	1	1
8	B	30	2	2	2
9	B	30	2	2	3    <------
10	B	20	4	3	4    <------
11	B	20	4	3	5    <------
12	B	10	6	4	6

从结果可以看出三者的区别:
row_number():不管值是否相同,都是连续排列,不跳跃---->可用作分页
rank():如果值相同,排序一样,后面的排序跳跃---->可用作学生分数排名
dense_rank():如果值相同,排序一样,后面的排序不跳跃

通常前面两个使用的比较多。

你可能感兴趣的:(Hive,#,Oracle,#,sql)