在Postgres的9.x中我可以这样做PostgreSQL的创建骨料与秩序和默认参数
select dept_id, string_agg(user_id, ':' order by user_id)
from dept_user
group by dept_id;
+---------+------------+
| dept_id | string_agg |
+---------+------------+
| d1 | u1:u2:u3 |
| d2 | u3:u4 |
+---------+------------+
但我的公司使用的Postgres 8.3,所以我觉得一个聚合函数可以像string_agg
create schema WMSYS;
create or replace function WMSYS.sf_concat(text,text) returns text as $$
select case when coalesce($1, '') <> '' then $1||','||$2 else $2 end;
$$ language sql called on null input;
create aggregate WMSYS.wm_concat (text) (sfunc=WMSYS.sf_concat,stype=text);
结果是:
select dept_id, WMSYS.wm_concat(user_id)
from dept_user
group by dept_id;
+---------+-----------+
| dept_id | wm_concat |
+---------+-----------+
| d1 | u3,u1,u2 |
| d2 | u3,u4 |
+---------+-----------+
但结果是没有排序(u3,u1,u2
应该是u1,u2,u3
)并且连接字符串(,
)不是参数。 我希望像这样使用:
WMSYS.wm_concat(user_id) ## join by ',' and don't sort
WMSYS.wm_concat(user_id, ':') ## join by ':' and don't sort
WMSYS.wm_concat(user_id, ':', true) ## join by ':' and order by user_id
该怎么做?
https://stackoverflow.com/a/2561297/330315和https://stackoverflow.com/q/16455483/330315 –