现有一张工资表,需要对其进行排名,工资相同的人并列排名,然后再排名,很多刚接触的小伙伴估计第一时间想到Rank()函数或row_number() 函数,但是结果出来后并不是自己想要的,在这里就给大家介绍下排序函数dense_rank()以及Rank()函数与row_number() 函数之间的区别。
本文用的是mysql 为8.0以上版本。
下面就用实例给大家演示一遍:
在Mysql数据库中创建一张雇员表employee:
-
create
table if
not
EXISTS `employee`
-
-
( `id`
int UNSIGNED AUTO_INCREMENT ,
-
-
`name`
varchar(
20)
not
null,
-
-
`salary`
int
not
null ,
-
-
PRIMARY KEY(`id`)
-
-
)ENGINE
=InnoDB
DEFAULT CHARSET
=utf8;
向employee表中插入数据:
-
-
insert
into employee (name,salary)
VALUES (
'张三',
12000);
-
insert
into employee (name,salary)
VALUES (
'李四',
12500);
-
insert
into employee (name,salary)
VALUES (
'王二麻子',
15000);
-
insert
into employee (name,salary)
VALUES (
'赵信',
13000);
-
insert
into employee (name,salary)
VALUES (
'关羽',
12500);
-
insert
into employee (name,salary)
VALUES (
'张飞',
13000);
查看创建的雇员表
select * from employee
分别用三种排序函数对salary字段进行排名:
-
select name ,
-
salary,
rank()
over (
ORDER
BY salary
desc)
as rank1,
-
ROW_NUMBER( )
over (
ORDER
BY salary
desc)
as ROW1,
-
DENSE_RANK( )
over (
ORDER
BY salary
desc)
as DENSE1
-
from employee
结果如下:
综合上面的结果可以得出结论:
1、rank 遇重复值排序并列,然后跳跃到当前排序记录次数开始(递增或递减)排序
2、row_number 遇重复值排序不并列,连续不间断(递增或递减)排序
3、dense_rank 遇重复值排序并列,然后继续不间断(递增或递减)排序
以上就是Rank、row_number、dense_rank 三种排序函数的区别啦,小伙伴们最好自己动手操作一遍,这样印象更深刻。