postgresql 数据库聚合函数 string_agg、array_agg

田成仁
2023-12-01

string_agg、array_agg 的作用和效果都差不多,只是转换后结果的数据类型不一致。

string_agg 函数

with tmp_t0 as (
    select 'A'::varchar as c1 union all
    select 'B'::varchar as c1 union all
    select 'C'::varchar as c1 
)
select string_agg(c1,',') 
  from tmp_t0
  ; 

 string_agg 
------------
 A,B,C
(1 row)

array_agg 函数

with tmp_t0 as (
    select 'A'::varchar as c1 union all
    select 'B'::varchar as c1 union all
    select 'C'::varchar as c1 
)
select array_agg(c1) 
  from tmp_t0
  ; 

 array_agg 
-----------
 {A,B,C}
(1 row)

参考:
https://www.postgresql.org/docs/9.6/static/functions-aggregate.html
https://www.postgresql.org/docs/9.6/static/functions-string.html

 类似资料: