sql - Postgresql GROUP_CONCAT equivalent? -
i have table , i'd pull 1 row per id field values concatenated.
in table, example, have this:
tm67 | 4 | 32556 tm67 | 9 | 98200 tm67 | 72 | 22300 tm99 | 2 | 23009 tm99 | 3 | 11200
and i'd output:
tm67 | 4,9,72 | 32556,98200,22300 tm99 | 2,3 | 23009,11200
in mysql able use aggregate function group_concat
, doesn't seem work here... there equivalent postgresql, or way accomplish this?
this starting point (version 8.4+ only):
select id_field, array_agg(value_field1), array_agg(value_field2) data_table group id_field
array_agg returns array, can cast text , edit needed (see clarifications, below).
prior version 8.4, have define prior use:
create aggregate array_agg (anyelement) ( sfunc = array_append, stype = anyarray, initcond = '{}' );
(paraphrased postgresql documentation)
clarifications:
- the result of casting array text resulting string starts , ends curly braces. braces need removed method, if not desired.
- casting anyarray text best simulates csv output elements contain embedded commas double-quoted in output in standard csv style. neither array_to_string() or string_agg() (the "group_concat" function added in 9.1) quote strings embedded commas, resulting in incorrect number of elements in resulting list.
- the new 9.1 string_agg() function not cast inner results text first. "string_agg(value_field)" generate error if value_field integer. "string_agg(value_field::text)" required. array_agg() method requires 1 cast after aggregation (rather cast per value).
Comments
Post a Comment