:MySQL开窗函数
Posted 浊酒南街
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了:MySQL开窗函数相关的知识,希望对你有一定的参考价值。
目录
1.创表语句
1.语法
mysql 8.0之后,开始支持开窗函数;
语法格式:row_number() over(partition by 分组列 order by 排序列 desc)
row_number() over()分组排序功能:
在使用 row_number() over()函数时候,over()里头的分组以及排序的执行晚于 where 、group by、 order by 的执行。
2.建表语句
create table TEST_ROW_NUMBER_OVER(
id varchar(10) not null,
name varchar(10) null,
age varchar(10) null,
salary int null
);
3.插入数据
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;
2.row_number()over
需求1:查询基本信息,并新加一列,按照工资降序排列
select id,name,age,salary,row_number()over(order by salary desc) rn
from TEST_ROW_NUMBER_OVER t
需求2:查询基本信息,并新加一列,先以id分组再按照工资降序排列
方法一:
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
需求3:查询基本信息,并新加一列,先以id分组再按照工资降序排列,并且排序数小于2
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
需求4:查询基本信息,并新加一列,以工资降序排列,并且选出年龄再13到16之间的;
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
)
在使用over等开窗函数时,over里头的分组及排序的执行晚于“where,group by,order by”的执行。
3.rank()over
需求1:查询基本信息,并新加一列,按照工资降序排列
select id,name,age,salary,rank()over(order by salary desc) rn
from TEST_ROW_NUMBER_OVER t
4.dense_rank()
需求1:查询基本信息,并新加一列,按照工资降序排列
select id,name,age,salary, DENSE_RANK() over(order by salary desc) rn
from TEST_ROW_NUMBER_OVER t
5.nitle()分组函数
需求1:查询基本信息,并新加一列分成4组,按照工资降序排列
select id,name,age,salary, NTILE(4) over(order by salary desc) rn
from TEST_ROW_NUMBER_OVER t
以上是关于:MySQL开窗函数的主要内容,如果未能解决你的问题,请参考以下文章