使用 string_agg 为 group_concat 聚合别名

soa*_*dos 5 postgresql group-concat

我知道 postgres 没有 group_concat,但我想通过使用 string_agg(或任何其他有效的方式)来模拟它的字符串。

由于无法更改遗留代码,我需要使用名为 group_concat 的函数。

我怎样才能做到这一点?

对于它的价值,我还尝试group_concat使用常规 concat 来实现,但也遇到了错误:

CREATE AGGREGATE group_concat (text) (sfunc = concat, stype=text)
Run Code Online (Sandbox Code Playgroud)

错误:

“函数 concat(text,text) 不存在”

Abe*_*sto 5

-- drop aggregate if exists group_concat(text);
CREATE AGGREGATE group_concat(text) (
  SFUNC=textcat,
  STYPE=text
);

select group_concat(x) from unnest('{a,b,c,d}'::text[]) as x;
Run Code Online (Sandbox Code Playgroud)

textcat||运算符内部使用的函数:

CREATE OPERATOR ||(
  PROCEDURE = textcat,
  LEFTARG = text,
  RIGHTARG = text);
Run Code Online (Sandbox Code Playgroud)

更新

将逗号作为分隔符:

--drop aggregate if exists group_concat(text);
--drop function if exists group_concat_trans(text, text);

create or replace function group_concat_trans(text, text)
  returns text
  language sql
  stable as 
$$select concat($1,case when $1 is not null and $2 is not null then ',' end,$2)$$;

create aggregate group_concat(text) (
  sfunc=group_concat_trans,
  stype=text);

select group_concat(x) from unnest(array['a','b','c',null,'d']) as x;
Run Code Online (Sandbox Code Playgroud)
??????????????????
? group_concat ?
??????????????????
? A B C D ?
??????????????????