MySQL 8.0之后,开始支持开窗函数;
语法格式:row_number() over(partition by 分组列 order by 排序列 desc)
row_number() over()分组排序功能:
在使用 row_number() over()函数时候,over()里头的分组以及排序的执行晚于 where 、group by、 order by 的执行。
create table TEST_ROW_NUMBER_OVER( id varchar(10) not null, name varchar(10) null, age varchar(10) null, salary int null );
insert into TEST_ROW_NUMBER_OVER(id,name,age,salary) values(1,'a',10,8000); insert into TEST_ROW_NUMBER_OVER(id,name,age,salary) values(1,'a2',11,6500); insert into TEST_ROW_NUMBER_OVER(id,name,age,salary) values(2,'b',12,13000); insert into TEST_ROW_NUMBER_OVER(id,name,age,salary) values(2,'b2',13,4500); insert into TEST_ROW_NUMBER_OVER(id,name,age,salary) values(3,'c',14,3000); insert into TEST_ROW_NUMBER_OVER(id,name,age,salary) values(3,'c2',15,20000); insert into TEST_ROW_NUMBER_OVER(id,name,age,salary) values(3,'d',16,30000); insert into TEST_ROW_NUMBER_OVER(id,name,age,salary) values(5,'d2',17,1800); insert into TEST_ROW_NUMBER_OVER(id,name,age,salary) values(3,'d2',18,50000);
select * from TEST_ROW_NUMBER_OVER t;
select id,name,age,salary,row_number()over(order by salary desc) rn from TEST_ROW_NUMBER_OVER t
方法一:
select id,name,age,salary,row_number()over(partition by id order by salary desc) rn from TEST_ROW_NUMBER_OVER t;
方法二:
select * from (select id,name,age,salary,row_number() over(partition by id order by salary desc) rn from TEST_ROW_NUMBER_OVER) t1
select * from (select id,name,age,salary,row_number() over(partition by id order by salary desc) rn from TEST_ROW_NUMBER_OVER) t1 where t1.rn<2
select id,name,age,salary,row_number()over(order by salary desc) rn from TEST_ROW_NUMBER_OVER t where t.age between '13' and '16'
with tabs as ( select id, name, age, salary, row_number()over(partition by id order by salary desc) rn from TEST_ROW_NUMBER_OVER t )
在使用over等开窗函数时,over里头的分组及排序的执行晚于“where,group by,order by”的执行。
select id,name,age,salary,rank()over(order by salary desc) rn from TEST_ROW_NUMBER_OVER t
select id,name,age,salary, DENSE_RANK() over(order by salary desc) rn from TEST_ROW_NUMBER_OVER t
select id,name,age,salary, NTILE(4) over(order by salary desc) rn from TEST_ROW_NUMBER_OVER t