I have a table and I'd like to pull one row per id with field values concatenated.
In my table, for example, I have this:
TM67 | 4 | 32556 TM67 | 9 | 98200 TM67 | 72 | 22300 TM99 | 2 | 23009 TM99 | 3 | 11200
And I'd like to output:
TM67 | 4,9,72 | 32556,98200,22300 TM99 | 2,3 | 23009,11200
In MySQL I was able to use the aggregate function GROUP_CONCAT
, but that doesn't seem to work here... Is there an equivalent for PostgreSQL, or another way to accomplish this?
The GROUP_CONCAT() function in MySQL is used to concatenate data from multiple rows into one field. This is an aggregate (GROUP BY) function which returns a String value, if the group contains at least one non-NULL value. Otherwise, it returns NULL.
PostgreSQL provides you with the CAST operator that allows you to do this. In this syntax: First, specify an expression that can be a constant, a table column, an expression that evaluates to a value. Then, specify the target data type to which you want to convert the result of the expression.
Since 9.0 this is even easier:
SELECT id, string_agg(some_column, ',') FROM the_table GROUP BY id
This is probably a good starting point (version 8.4+ only):
SELECT id_field, array_agg(value_field1), array_agg(value_field2) FROM data_table GROUP BY id_field
array_agg returns an array, but you can CAST that to text and edit as needed (see clarifications, below).
Prior to version 8.4, you have to define it yourself prior to use:
CREATE AGGREGATE array_agg (anyelement) ( sfunc = array_append, stype = anyarray, initcond = '{}' );
(paraphrased from the PostgreSQL documentation)
Clarifications:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With