rank() within group()用法

select rank(1500) within group (order by salary desc) "rank of 1500" from employees;

实际得到的结果就是:
如果存在一条记录,这条记录的salary字段值为1500。
那么将该条记录插入employees表中后,按照salary字段降序排列后,该条记录的序号为多少?
比如原表employees内容如下
SQL> select * from employees;


EMP_ID     EMP_NAME         SALARY
---------- -------------------- ----------
10001      ZhangSan              500
10002      LiSi                        1000
10003      WangWu               1500
10004      MaLiu                     2000
10005      NiuQi                      2500


则如果一个员工的薪水为1500,那么该员工在员工表中的薪水排名应与WangWu相同,并列排名第三。
通过聚合函数RANK() WITHIN GROUP验证一下:
SQL> select rank(1500) within group (order by salary) as "rank number" from employees;
rank number
-----------
          3


若原表内容如下
SQL> select * from employees;


EMP_ID     EMP_NAME         SALARY
---------- -------------------- --------------
10001      ZhangSan             500
10004      MaLiu                    2000
10005      NiuQi                    2500


则排名应为第2,验证如下
SQL> select rank(1500) within group (order by salary) as "rank number" from employees;
rank number
-----------
          2

猜你喜欢

转载自blog.csdn.net/aoc212/article/details/9225077