【发布时间】:2017-09-16 13:39:38
【问题描述】:
在 Postgres 9.x 中我可以这样做
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
怎么做?
【问题讨论】:
标签: sql postgresql aggregate plpgsql