创建表的语句
语法格式: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
);
select * from TEST_ROW_NUMBER_OVER t;
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(4,'d',16,30000);
row_number()over
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
没有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的用法
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
)
select *
from tabs where rn=1;
在使用over等开窗函数时,over里头的分组及排序的执行晚于“where,group by,order by”的执行。
rank()over
select id,name,age,salary,rank()over(order by salary desc) rn
from TEST_ROW_NUMBER_OVER t
DENSE_RANK()
select id,name,age,salary, DENSE_RANK() over(order by salary desc) rn
from TEST_ROW_NUMBER_OVER t
NTILE(4)分组函数,分成4个组
select id,name,age,salary, NTILE(4) over(order by salary desc) rn
from TEST_ROW_NUMBER_OVER t
mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> select host, user, authentication_string, plugin from user;
flush privileges;