作者
digoal
日期
2020-06-25
标签
PostgreSQL , Hypothetical-Set Aggregate Functions , 假设 , 聚合
背景
《PostgreSQL aggregate function 4 : Hypothetical-Set Aggregate Functions》
https://www.postgresql.org/docs/devel/functions-aggregate.html
假设聚合函数, 聚合函数的一种类型,
例如假设我化学得了98分, 应该是班里第几名.
假设我的语文得了89分, 应该排在班级前百分之多少.
例子
```
postgres=# SELECT x % 2 AS grp, array_agg(x order by x),
rank(3.5) WITHIN GROUP (ORDER BY x)
FROM generate_series(1, 10) AS x
GROUP BY x % 2;
grp | array_agg | rank
-----+--------------+------
0 | {2,4,6,8,10} | 2
1 | {1,3,5,7,9} | 3
(2 rows)
postgres=# SELECT x % 2 AS grp, array_agg(x order by x),
percent_rank(3.5) WITHIN GROUP (ORDER BY x)
FROM generate_series(1, 10) AS x
GROUP BY x % 2;
grp | array_agg | percent_rank
-----+--------------+--------------
0 | {2,4,6,8,10} | 0.2
1 | {1,3,5,7,9} | 0.4
(2 rows)
```
rank ( args ) WITHIN GROUP ( ORDER BY sorted_args ) → bigint
Computes the rank of the hypothetical row, with gaps; that is, the row number of the first row in its peer group.
dense_rank ( args ) WITHIN GROUP ( ORDER BY sorted_args ) → bigint
Computes the rank of the hypothetical row, without gaps; this function effectively counts peer groups.
percent_rank ( args ) WITHIN GROUP ( ORDER BY sorted_args ) → double precision
Computes the relative rank of the hypothetical row, that is (rank - 1) / (total rows - 1). The value thus ranges from 0 to 1 inclusive.
cume_dist ( args ) WITHIN GROUP ( ORDER BY sorted_args ) → double precision
Computes the cumulative distribution, that is (number of rows preceding or peers with hypothetical row) / (total rows). The value thus ranges from 1/N to 1.
PostgreSQL 许愿链接
您的愿望将传达给PG kernel hacker、数据库厂商等, 帮助提高数据库产品质量和功能, 说不定下一个PG版本就有您提出的功能点. 针对非常好的提议,奖励限量版PG文化衫、纪念品、贴纸、PG热门书籍等,奖品丰富,快来许愿。开不开森.