In Postgres 9.x I can do like this
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 |
+---------+------------+
But my company uses Postgres 8.3, so I find a aggregate function can do like 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);
the result is:
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 |
+---------+-----------+
But the result is not sorted(u3,u1,u2
should be u1,u2,u3
) and join string(,
) is not a parameter.
I want usage like this:
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
how to do that?