postgresql 分类排名

postgresql 分类排名

排名窗口函数

排名窗口函数用于对数据进行分组排名。常见的排名窗口函数包括:

ROW_NUMBER ,为分区中的每行数据分配一个序列号,序列号从 1 开始分配。

RANK ,计算每行数据在其分区中的名次;如果存在名次相同的数据,后续的排名将会

产生跳跃。

DENSE_RANK ,计算每行数据在其分区中的名次;即使存在名次相同的数据,后续的

排名也是连续的值。

PERCENT_RANK ,以百分比的形式显示每行数据在其分区中的名次;如果存在名次相

同的数据,后续的排名将会产生跳跃。

CUME_DIST ,计算每行数据在其分区内的累积分布,也就是该行数据及其之前的数据

的比率;取值范围大于 0 并且小于等于 1。

NTILE ,将分区内的数据分为 N 等份,为每行数据计算其所在的位置。

排名窗口函数不支持动态的窗口大小(frame_clause),而是以当前分区作为分析的窗口。

示例

按照部门为单位,计算员工的月薪排名:

sql 复制代码
select
first_name,last_name,department_id,salary,
row_number() over(partition by department_id order by salary desc),
rank() over(partition by  department_id order by salary desc),
dense_rank() over(partition by  department_id order by salary desc),
percent_rank() over(partition by  department_id order by salary desc)
from employees;

以上示例中 4 个窗口函数的 OVER 子句完全相同,此时可以采用一种更简单的写法:

sql 复制代码
select
first_name,last_name,department_id,salary,
row_number() over w,
rank() over w,
dense_rank() over w,
percent_rank() over w
from employees
window w as  (partition by  department_id order by salary desc);

CUME_DIST 和 NTILE

sql 复制代码
select
first_name,last_name,department_id,salary,
cume_dist() over w,
ntile(6) over w
from employees
window w as  (partition by department_id order by salary desc);
相关推荐
zxrhhm1 天前
PostgreSQL 中的层级查询 Oracle CONNECT BY 替代方案
数据库·postgresql·oracle
梦想画家1 天前
PostgreSQL 图计算双雄:Apache AGE 与 pgGraphBLAS 的融合实战指南
数据库·postgresql·图算法
晚风_END1 天前
Linux|操作系统|zfs文件系统的使用详解
linux·运维·服务器·数据库·postgresql·性能优化·宽度优先
梦想画家2 天前
PostgreSQL 物化视图实战:从数据固化到智能刷新的全链路指南
数据库·postgresql·物化视图
Database_Cool_2 天前
在 RDS PostgreSQL 中实现 RaBitQ 量化
数据库·阿里云·ai·postgresql
道法自然,人法天2 天前
PostgreSQL安装与初始化教程(二进制压缩包)
数据库·postgresql
yzs872 天前
从Hydra到storage_engine:PostgreSQL列存引擎的性能跃迁与技术进化
数据库·postgresql
张~颜2 天前
autovacuum
数据库·postgresql
BU摆烂会噶3 天前
【LangGraph】持久化实现的三大能力——时间旅行
数据库·人工智能·python·postgresql·langchain