首页 > 数据库 >PLSQL ROW_NUMBER() OVER()函数的使用

PLSQL ROW_NUMBER() OVER()函数的使用

时间:2023-02-28 15:34:32浏览次数:48  
标签:salary over PLSQL OVER NUMBER number age id row

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


场景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) rank
  FROM test_row_number_over t;

场景3: 再一次排序:找出每一组中序号为一的数据

SELECT *
  FROM (SELECT id,
               NAME,
               age,
               salary,
               row_number() over(PARTITION BY id ORDER BY salary DESC) rank
          FROM test_row_number_over t)
 WHERE rank < 2;


场景4: 找出年龄在13岁到16岁数据,按salary排序

SELECT id, NAME, age, salary, row_number() over(ORDER BY salary DESC) rank
  FROM test_row_number_over t
 WHERE age BETWEEN '13' AND '16';

结果表明:rank 的序号,其实就表明了 over(order by salary desc) 是在where age between and 后执行的

用法1:使用row_number()函数进行编号,如

SELECT NAME, id, row_number() over(ORDER BY age) AS rn
  FROM test_row_number_over;

原理:先按age进行排序,排序完后,给每条数据进行编号

用法2: 按id的升序进行排序,并给每条记录进行排序代码如下:

SELECT NAME, id, row_number() over(ORDER BY  id) AS rn
  FROM test_row_number_over;

用法3:统计名字并按每一个名字下的年龄升序排序(默认是升序),同时给每一个年龄的名字进行编号。这样就知道每个名字有几个年龄了:

SELECT row_number() over(PARTITION BY NAME ORDER BY id) AS rn,
       NAME,
       id,
       age
  FROM test_row_number_over;

用法4:统计每一个名字排行第几

WITH tabs AS
 (SELECT row_number() over(PARTITION BY NAME ORDER BY age) AS rn,
         NAME,
         id,
         age
    FROM test_row_number_over)
SELECT MAX(rn) AS numb, NAME FROM tabs GROUP BY NAME;

标签:salary,over,PLSQL,OVER,NUMBER,number,age,id,row
From: https://www.cnblogs.com/dengxing/p/17164246.html

相关文章