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);
相关推荐
IvorySQL15 小时前
云环境下PostgreSQL的Cgroup内存管理实践
java·数据库·postgresql
IvorySQL1 天前
PG 日报|SQL/PGQ 图查询基于联接重写机制实现
数据库·人工智能·sql·postgresql·区块链·ivorysql
IvorySQL1 天前
深度拆解 IvorySQL 去 O 核心解决方案
数据库·人工智能·postgresql
大猫会长1 天前
mac安装PostgreSQL18笔记
postgresql
IvorySQL2 天前
PG 日报|新增 VACUUM 全维度统计信息补丁迭代
数据库·人工智能·postgresql·ivorysql
运维老郭2 天前
PostgreSQL编译安装实战
运维·postgresql
l1t3 天前
DeepSeek总结的RegreSQL 2.0测试通过了。计划却没通过。
linux·数据库·postgresql
ls_elect3 天前
PostgreSQL 18.4 SCRAM-SHA-256 认证故障诊断及修复办法
linux·数据库·postgresql
IvorySQL3 天前
PG 日报|社区讨论重构 pg_hba 配置文件格式
数据库·人工智能·postgresql·重构·ivorysql
weixin_307779134 天前
Linux下Docker Compose里运行PostgreSQL数据库故障诊断Shell脚本
linux·运维·数据库·docker·postgresql