MySQL开窗函数

MySQL开窗函数

知识点

三种开窗函数:row_number(),rank(),dense_rank() 这三种函数都是用于返回结果集的分组内每行的排名
区别:
    row_number():特点是唯一且连续,如果四个人是按成绩排名,那么是1234这样排的,即使有重分的人
	rank(): 特点是并列不连续,如果四个人是按成绩排名,那么是1224这样排的,重分的人是同一个排名,且占一个排名的位置,排名不连续
	dense_rank():特点是并列且连续,如果四个人是按成绩排名,那么是1223这样排的,重分的人是同一个排名,共占一个排名,排名连续

示例

# 三种排序函数: row_number() rank()  dense_rank()
# 数据准备
create table employee (
empid int,ename varchar(20) ,deptid varchar(10) ,salary decimal(10,2)
);

insert into employee values(1,'刘备','蜀',5500.00);
insert into employee values(2,'赵云','蜀',4500.00);
insert into employee values(3,'张飞','蜀',3500.00);
insert into employee values(4,'关羽','蜀',4500.00);

insert into employee values(5,'曹操','魏',1900.00);
insert into employee values(6,'许褚','魏',4800.00);
insert into employee values(7,'张辽','魏',6500.00);
insert into employee values(8,'徐晃','魏',14500.00);

insert into employee values(9,'孙权','吴',44500.00);
insert into employee values(10,'周瑜','吴',6500.00);
insert into employee values(11,'陆逊','吴',7500.00);


# 需求一: 使用三种排序函数对employee表中员工按照薪资进行降序排名:
select *,row_number() over (order by salary desc) as rank1,rank() over (order by salary desc)as rank2,dense_rank() over (order by salary desc)as rank3 from employee;

# 需求二: 对employee表中按照deptid进行分组,并对每一组的员工按照薪资进行降序排名:
select *,row_number() over (partition by deptid order by salary desc) as rank1,rank() over (partition by deptid order by salary desc)as rank2,dense_rank() over (partition by deptid order by salary desc)as rank3 from employee;

#开窗函数经常用于解决TOP N问题

热门相关:超武穿梭      横行霸道   特工重生:快穿全能女神   豪门重生盛世闲女