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);
相关推荐
审判长烧鸡1 小时前
GO时区【3】字段与连接设置
postgresql·go
qq_283720052 小时前
Python3 模块精讲:psycopg2(第三方)- 连接 PostgreSQL
数据库·postgresql
Mr.朱鹏12 小时前
【Python 进阶 | 第四篇】Psycopg3 + Flask 实现 PostgreSQL CRUD 全流程:从连接池到RESTful接口
python·postgresql·flask·virtualenv·fastapi·pip·tornado
瀚高PG实验室2 天前
pgroonga全文检索插件的BUG
数据库·postgresql·bug·瀚高数据库
hudson20222 天前
Postgres 实现自增的三种方式
postgresql
dblens 数据库管理和开发工具2 天前
DBLens for PostgreSQL 正式发布|把 PostgreSQL 开发与管理带进 AI + Agent 时代
数据库·人工智能·postgresql
l1t3 天前
DeepSeek总结的面向 PostgreSQL 分析和 HTAP 工作负载的两种高性能表访问方法
数据库·postgresql
老年DBA3 天前
PostgreSQL 高负载 Load Average 暴涨 | BufferMapping LWLock 锁竞争 完整排查优化实战
数据库·postgresql
脑子进水养啥鱼?3 天前
PostgreSql CAST
数据库·postgresql
Mrssory3 天前
Postgresql数据库快速入门
数据库·postgresql