Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make array_agg() work like group_concat() from mySQL

So I have this table:

create table test (    id integer,     rank integer,    image varchar(30) );  

Then some values:

id | rank | image    ---+------+-------    1 |    2 | bbb    1 |    3 | ccc    1 |    1 | aaa    2 |    3 | c    2 |    1 | a    2 |    2 | b   

I want to group them by id and concatenate the image name in the order given by rank. In mySQL I can do this:

  select id,           group_concat( image order by rank asc separator ',' )      from test  group by id; 

And the output would be:

 1 aaa,bbb,ccc 2 a,b,c 
Is there a way I can have this in postgresql?

If I try to use array_agg() the names will not show in the correct order and apparently I was not able to find a way to sort them. (I was using postgres 8.4 )

like image 843
user491575 Avatar asked Oct 29 '10 17:10

user491575


People also ask

What is Group_concat in MySQL?

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.

What does Array_agg return?

Returns the input values, pivoted into an ARRAY. If the input is empty, an empty ARRAY is returned.

What is Array_agg?

The ARRAY_AGG() accepts an expression that returns a value of any type which is valid for an array element. The ORDER BY clause is an optional clause. It specifies the order of rows processed in the aggregation, which determines the order of the elements in the result array.


1 Answers

In PostgreSQL 8.4 you cannot explicitly order array_agg but you can work around it by ordering the rows passed into to the group/aggregate with a subquery:

SELECT id, array_to_string(array_agg(image), ',') FROM (SELECT * FROM test ORDER BY id, rank) x GROUP BY id; 

In PostgreSQL 9.0 aggregate expressions can have an ORDER BY clause:

SELECT id, array_to_string(array_agg(image ORDER BY rank), ',') FROM test GROUP BY id; 
like image 199
Jason Weathered Avatar answered Sep 28 '22 04:09

Jason Weathered