Dans Postgres 9.x je peux faire comme çapostgresql créer ensemble avec commande par défaut et le paramètre
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 |
+---------+------------+
Mais ma compagnie utilise Postgres 8.3, donc je trouve une fonction d'agrégation peut faire comme 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);
le résultat est:
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 |
+---------+-----------+
Mais le résultat n'est pas trié (u3,u1,u2
doit être u1,u2,u3
) et la chaîne de jointure (,
) n'est pas un paramètre. Je veux utilisation comme ceci:
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
comment faire?
https://stackoverflow.com/a/2561297/330315 et https://stackoverflow.com/q/16455483/330315 –