MySQL开窗函数

文章目录

      • 创建表的语句
      • row_number()over
      • rank()over
      • DENSE_RANK()
      • NTILE(4)分组函数,分成4个组

创建表的语句

语法格式: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

MySQL开窗函数_第1张图片

select id,name,age,salary,row_number()over(partition by id order by salary desc) rn from TEST_ROW_NUMBER_OVER t;

MySQL开窗函数_第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

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

MySQL开窗函数_第3张图片

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'

MySQL开窗函数_第4张图片

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

MySQL开窗函数_第5张图片

DENSE_RANK()

select id,name,age,salary, DENSE_RANK() over(order by salary desc) rn
from TEST_ROW_NUMBER_OVER t

MySQL开窗函数_第6张图片

NTILE(4)分组函数,分成4个组

select id,name,age,salary, NTILE(4)  over(order by salary desc) rn
from TEST_ROW_NUMBER_OVER t

MySQL开窗函数_第7张图片

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; 

MySQL开窗函数_第8张图片

flush privileges;

你可能感兴趣的:(实用工具,实用技术)