↑↓ 选择↵ 打开⌫ 切换范围完整搜索

PG.CENTER 连接 PostgreSQL 文档、百科与生态知识。由 Pigsty 维护。

支持中的版本: 当前版本 (18) / 17 / 16 / 15 / 14
开发中的版本: 19 / 20devel
已结束支持的版本: 13 / 12 / 11 / 10 / 9.6 / 9.5 / 9.4 / 9.3 / 9.2 / 9.1 / 9.0 / 8.4 / 8.3 / 8.2 / 8.1 / 8.0 / 7.4 / 7.3 / 7.2 / 7.1
历史版本。 PostgreSQL 8.3 已结束支持。 请参阅 当前版本手册.

9.3. 数学函数和操作符 #

PostgreSQL为很多类型提供了数学操作符。对于那些没有标准数学惯例的类型(如日期/时间类型),我们将在后续小节中描述实际的行为。

表 9.2列出了可用的数学操作符。

表 9.2. 数学操作符

Operator描述示例Result
+ 加法2 + 35
- 减法2 - 3-1
* 乘法2 * 36
/ 除法(整数除法会截断结果)4 / 22
% 取模(余数)5 % 41
^ 求幂(从左向右结合)2.0 ^ 3.08
|/ 平方根|/ 25.05
||/ 立方根||/ 27.03
! 阶乘5 !120
!! 阶乘(前缀操作符)!! 5120
@ 绝对值@ -5.05
& 按位与91 & 1511
| 按位或32 | 335
# 按位异或17 # 520
~ 按位非~1-2
<< 按位左移1 << 416
>> 按位右移8 >> 22

按位操作符仅适用于整数数据类型,而其他操作符适用于所有数值数据类型。按位操作符也可用于位串类型 bit 和 bit varying,如表 9.10所示。

表 9.3列出了可用的数学函数。表中的 dp 表示 double precision。许多函数提供了参数类型不同的多种形式。除非另有说明,函数的每种形式都返回与其参数相同的数据类型。处理 double precision 数据的函数大多基于主机系统的 C 库实现;因此,其精度和边界情况下的行为可能因主机系统而异。

表 9.3. 数学函数

FunctionReturn Type描述示例Result
abs(x)(与x相同)绝对值abs(-17.4)17.4
cbrt(dp)dpcube rootcbrt(27.0)3
ceil(dp or numeric)(与输入相同)不小于参数的最小整数ceil(-42.8)-42
ceiling(dp or numeric)(与输入相同)不小于参数的最小整数(ceil的别名)ceiling(-95.3)-95
degrees(dp)dp弧度转换为角度degrees(0.5)28.6478897565412
exp(dp or numeric)(与输入相同)指数函数exp(1.0)2.71828182845905
floor(dp or numeric)(与输入相同)不大于参数的最大整数floor(-42.8)-43
ln(dp or numeric)(与输入相同)自然对数ln(2.0)0.693147180559945
log(dp or numeric)(与输入相同)以 10 为底的对数log(100.0)2
log(b numeric, x numeric)numeric以 b 为底的对数log(2.0, 64.0)6.0000000000
mod(y, x)(与参数类型相同)y/x的余数mod(9,4)1
pi()dp“π” constantpi()3.14159265358979
power(a dp, b dp)dp a的b次幂 power(9.0, 3.0)729
power(a numeric, b numeric)numeric a的b次幂 power(9.0, 3.0)729
radians(dp)dp角度转换为弧度radians(45.0)0.785398163397448
random()dp0.0 <= x < 1.0 范围内的随机值random() 
round(dp or numeric)(与输入相同)舍入到最接近的整数round(42.4)42
round(v numeric, s int)numeric舍入到 s 位小数round(42.4382, 2)42.44
setseed(dp)void为后续random()调用设置种子(值介于 0 和 1.0 之间)setseed(0.54823) 
sign(dp or numeric)(与输入相同)参数的符号(-1、0、+1)sign(-8.4)-1
sqrt(dp or numeric)(与输入相同)平方根sqrt(2.0)1.4142135623731
trunc(dp or numeric)(与输入相同)向零截断trunc(42.8)42
trunc(v numeric, s int)numeric截断到 s 位小数trunc(42.4382, 2)42.43
width_bucket(op numeric, b1 numeric, b2 numeric, count int)int返回 operand 在等宽直方图(在 b1 到 b2 的范围内有 count 个桶)中所属的桶编号width_bucket(5.35, 0.024, 10.06, 5)3
width_bucket(op dp, b1 dp, b2 dp, count int)int返回 operand 在等宽直方图(在 b1 到 b2 的范围内有 count 个桶)中所属的桶编号width_bucket(5.35, 0.024, 10.06, 5)3

最后,表 9.4列出了可用的三角函数。所有三角函数都接受double precision类型的参数并返回该类型的值。

表 9.4. 三角函数

Function描述
acos(x)inverse cosine
asin(x)inverse sine
atan(x)inverse tangent
atan2(y, x)inverse tangent of y/x
cos(x)cosine
cot(x)cotangent
sin(x)sine
tan(x)tangent

报告文档问题

阅读 上游文档. 反馈更正前请先核对 当前版本手册.