sql排序函数 rank() / dense_rank()

Rank排名函数

1、rank()

按照某字段的排序结果添加排名,但是他是跳跃的、间断的排名

partition by子句按照对应字段将结果集分为多个分区,然后order by子句按分数对结果集进行排序

RANK() OVER (
   PARTITION BY <expression>[{,<expression>...}]
   ORDER BY <expression> [ASC|DESC], [{,<expression>...}]
)

例:按照score进行排名

SELECT score, rank() over(ORDER BY score desc) as 'Rank'
FROM rank;
-->
+------+---------+
| score|   Rank  |
+------+---------+
|  100 |       1 |
|  100 |       1 |
|  95  |       3 |
|  95  |       3 |
|  95  |       3 |
|  90  |       6 |
|  89  |       7 |
+------+---------+

按照name进行分区,根据分数进行排名

select name, score ,rank() over(partition by name, order by score desc) 'Rank'
from rankl;
+------+------+---------+
| name | score|   Rank  |
+------+------+---------+
| a   |  100 |       1 |
| a   |  90  |       2 |
| a   |  89  |       3 |
| b   |  100 |       1 |
| c   |  95  |       1 |
| d   |  95  |       1 |
| e   |  95  |       1 |
+------+------+---------+

2、dense_rank()

dense_rank()是的排序数字是连续的、不间断。当有相同的分数时,它们的排名结果是并列的,例如,1,2,2,3。

DENSE_RANK() OVER (
   PARTITION BY <expression>[{,<expression>...}]
   ORDER BY <expression> [ASC|DESC], [{,<expression>...}]
)

例:leetcode178. 分数排名

select score, dense_rank() over(order by score desc) 'rankd'
from Scores
输入:
Scores 表:
+----+-------+
| id | score |
+----+-------+
| 1  | 3.50  |
| 2  | 3.65  |
| 3  | 4.00  |
| 4  | 3.85  |
| 5  | 4.00  |
| 6  | 3.65  |
+----+-------+
输出:
+-------+------+
| score | rank |
+-------+------+
| 4.00  | 1    |
| 4.00  | 1    |
| 3.85  | 2    |
| 3.65  | 3    |
| 3.65  | 3    |
| 3.50  | 4    |
+-------+------+

例:leetcode185. 部门工资前三高的所有员工

从子表r中查询,子表包括需要查出来的字段,以及薪水rank排位,按部门id分组查询出每组(每部门)薪水从低到高的排名,然后外层查询的时候,只筛选rank排位在前三的人就行

select Department,Employee,Salary
from (select d.name Department, e.name Employee, e.salary Salary, dense_rank() over(partition by d.id order by e.salary desc)  'rank'
     from Employee e, Department d
     where e.departmentId = d.id
) r
where r.rank <= 3 ;

posted on   老菜农  阅读(395)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示

导航

统计信息

点击右上角即可分享
微信分享提示