电脑技术学习

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

dn001

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

 digoal***zhou

(1 row)

计算总和, sum不计算null, 当所有行都是null时, 即没有任何行输入, 返回null.

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

 sum 

   3

(1 row)

postgres=# select sum(id::int) from (values(null),(null),(null)) as t(id);

 sum 

-----

(1 row)

聚合后得到xml

postgres=# select xmlagg(id::xml) from (values(null),('digoal'),('')) as t(id);

         xmlagg          

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

 digoal

(1 row)

某些聚合函数得到的结果可能和行的输入顺序有关, 例如array_agg, json_agg, json_object_agg, string_agg, and xmlagg, 以及某些自定义聚合函数. 如何来实现呢? 支持聚合函数中使用order by的PostgreSQL版本可以用如下语法 :

postgres=# select string_agg(id,'***' order by id) from (values(null),('digoal'),('zhou')) as t(id);

  string_agg   

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

 digoal***zhou

(1 row)

postgres=# select string_agg(id,'***' order by id desc) from (values(null),('digoal'),('zhou')) as t(id);

  string_agg   

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

 zhou***digoal

(1 row)

不支持聚合函数中使用order by的PostgreSQL版本, 可以用如下语法 : 

SELECT xmlagg(x) FROM (SELECT x FROM test ORDER BY y DESC) AS tab;

postgres=# select string_agg(id,'***') from (select id from (values(null),('digoal'),('zhou')) as t(id) order by id desc) t;

  string_agg   

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

 zhou***digoal

(1 row)

标签:

上一篇 PostgreSQL新手入门

下一篇 返回列表