width_bucket() 是一个系统函数,它根据给定的直方图或数组,返回一个操作数所属桶的编号。
width_bucket() 函数于 PostgreSQL 8.0 中添加。
用法
width_bucket() 有两个变体,一个操作于直方图,另一个操作于 数组。
直方图
width_bucket (operandnumeric,lownumeric,highnumeric,countinteger)
→integer
width_bucket (operanddouble precision,lowdouble precision,highdouble precision,countinteger)
→integer
如果提供的 operand 超出了直方图的下界或上界,将返回 0 或 count + 1。
数组
width_bucket (operandanycompatible,thresholdsanycompatiblearray)
→integer
提供的数组必须已排序,值从小到大排列,否则可能会返回不正确的结果。
如果提供的 operand 超出了数组的下界或上界,将返回 0 或 array_length() + 1。
变更历史
- PostgreSQL 19
- 非数组变体现在允许
operand输入为NaN(commit 7374b3a5)
- 非数组变体现在允许
- PostgreSQL 9.5
- 添加了数组变体 (commit e80252d4)
- PostgreSQL 8.3
- 添加了
double precision变体 (commit cf57ef4e)
- 添加了
- PostgreSQL 8.0
- 已添加 (commit 0079547b)
示例
使用直方图的 width_bucket() 的基本用法示例
postgres=# SELECT width_bucket(13, 11, 15, 5);
width_bucket
--------------
3
(1 row)
在此示例中,直方图的范围是 11 到 15,包含 5 个桶。相应地,提供的 operand 3 位于第三个桶中。
使用非整数值的示例
postgres=# SELECT width_bucket(0.3, 0.1, 1.1, 5);
width_bucket
--------------
2
(1 row)
如果提供的 operand 低于直方图的下界,则返回 0
postgres=# SELECT width_bucket(2, 11, 15, 5);
width_bucket
--------------
0
(1 row)
如果提供的 operand 高于直方图的上界,则返回 count + 1
postgres=# SELECT width_bucket(22, 11, 15, 5);
width_bucket
--------------
6
(1 row)
使用数组的 width_bucket() 的基本用法示例
postgres=# SELECT width_bucket(2, ARRAY[1, 2, 3]);
width_bucket
--------------
2
(1 row)
参考资料
- PostgreSQL 文档: 数学函数
