聚合函数从一组输入值中计算出一个单一的结果值。表 6.33展示了内置的聚合函数。聚合函数的特殊语法考虑在第 1.2.5 节中解释。更多介绍信息请参阅 PostgreSQL 教程。
表 6.33. 聚合函数
| 函数 | 参数类型 | 返回类型 | 描述 | |
|---|
avg(expression)
| smallint, integer,
bigint, real, double
precision, numeric, or interval.
| 整数类型参数为numeric,浮点参数为double precision,否则与参数数据类型相同
| 所有输入值的平均值(算术平均) | |
count(*) | | bigint | 输入值的数目 | |
count(expression) | 任意类型 | bigint | expression 的值不为 null 的输入行数 | |
max(expression) | 任意数字、字符串或日期/时间类型 | 与参数类型相同 | expression 在所有输入值中的最大值
| |
min(expression) | 任意数字、字符串或日期/时间类型 | 与参数类型相同 | expression 在所有输入值中的最小值
| |
stddev(expression)
| smallint, integer,
bigint, real, double
precision, or numeric.
| 浮点参数为 double precision,否则为 numeric。
| 输入值的样本标准差 | |
sum(expression) | smallint, integer,
bigint, real, double
precision, numeric, or interval
| smallint或integer参数为bigint,bigint参数为numeric,浮点参数为double precision,否则与参数数据类型相同
| expression 在所有输入值上的总和 | |
variance(expression)
| smallint, integer,
bigint, real, double
precision, or numeric.
| 浮点参数为 double precision,否则为 numeric。
| 输入值的样本方差(样本标准差的平方) | |
应当注意,除了 count 之外,这些函数在没有选中任何行时都返回空值。特别地,没有行时 sum 返回空值,而不是人们可能预期的零。必要时可以使用 coalesce
函数把空值替换为零。