电脑技术学习

PostgreSQL 聚合函数讲解 - 常用聚合函数

dn001

PostgreSQL支持较多的聚合函数, 以PostgreSQL 9.4为例, 支持例如一般性的聚合, 统计学科的聚合, 排序集聚合, 假象集聚合等.

本文将对一般性聚合函数举例说明其功能和用法.

聚合函数有哪些,见 : http://www.postgresql.org/docs/9.4/static/functions-aggregate.html

以上所有聚合函数, 当没有行输入时, 除了count返回0, 其他都返回null.

使用sum, array_agg时, 当没有行输入, 返回NULL可能有点别扭, 那么你可以使用coalesce来替代NULL, 如coalesce(sum(x), 0) coalesce(array_agg(x), '{}'::int[])

例子 : 聚合后得到数组, null将计入数组元素

postgres=# select array_agg(id) from (values(null),(1),(2)) as t(id);

 array_agg  

------------

 {NULL,1,2}

(1 row)

算平均值是不计算null

postgres=# select avg(id) from (values(null),(1),(2)) as t(id);

        avg         

--------------------

 1.5000000000000000

(1 row)

算bit与|或 时也不计算NULL

postgres=# select bit_and(id) from (values(null),(1),(2)) as t(id);

 bit_and 

---------

       0

(1 row)

postgres=# select bit_or(id) from (values(null),(1),(2)) as t(id);

 bit_or 

--------

      3

(1 row)

算布尔逻辑时也不计算NULL

postgres=# select bool_and(id) from (values(null),(true),(false)) as t(id);

 bool_and 

----------

 f

(1 row)

every是bool_and的别名, 实际上是SQL标准中定义的. 

postgres=# select every(id) from (values(null),(true),(false)) as t(id);

 every 

-------

 f

(1 row)

SQL标准中还定义了any和some为bool_or的别名, 但是因为any和some还可以被解释为子查询, 所以在PostgreSQL中any和some的布尔逻辑聚合不可用.

postgres=# select any(id) from (values(null),(true),(false)) as t(id);

ERROR:  syntax error at or near "any"

LINE 1: select any(id) from (values(null),(true),(false)) as t(id);

               ^

postgres=# select some(id) from (values(null),(true),(false)) as t(id);

ERROR:  syntax error at or near "some"

LINE 1: select some(id) from (values(null),(true),(false)) as t(id);

标签:

上一篇 PostgreSQL新手入门

下一篇 返回列表