Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to aggregate two PostgreSQL columns to an array separated by brackets

Tags:

I would like to concatenate two columns using a group-by query resulting in an array separed with brackets. I know this question is related to this question, but as usual my use-case is a little different.

A simple example (also as SQL Fiddle). Currently my query returns the following:

ID  X   Y 3   0.5 2.71 3   1.0 2.50 3   1.5 2.33 6   0.5 2.73 6   1.5 2.77 

But where I would like concatenate/aggregate the X/Y columns to get the following:

ID  XY 3   [[0.5,2.71],[1.0,2.50],[1.5,2.33]] 6   [[0.5,2.73],[1.5,2.77]] 

Currently I've tried to concatenate the columns into one as follows:

SELECT "ID",concat_ws(', ',"X", "Y") as XY FROM Table1; 

Which returns:

ID  xy 3   0.5, 2.71 3   1, 2.50 3   1.5, 2.33 6   0.5, 2.73 

And used array_agg():

SELECT "ID",array_to_string(array_agg("X"),',') AS XY FROM Table1 GROUP BY "ID"; 

Resulting in:

ID  xy 3   0.5,1,1.5 6   0.5 

I feel I'm getting closer, but a helping hand would be really appreciated.

like image 530
Mattijn Avatar asked Aug 29 '16 18:08

Mattijn


People also ask

What is [] in PostgreSQL?

We access array elements using the subscript within square brackets [] . By default, PostgreSQL uses one-based numbering for array elements.

What is Unnest in PostgreSQL?

The purpose of unnest function in PostgreSQL is to expand the array into rows. Unnest function generates a table structure of an array in PostgreSQL. Unnest array function is beneficial in PostgreSQL for expanding the array into the set of values or converting the array into the structure of the rows.

What is Array_agg in Postgres?

PostgreSQL ARRAY_AGG() function is an aggregate function that accepts a set of values and returns an array where each value in the input set is assigned to an element of the array.


1 Answers

Create an array from the two columns, the aggregate the array:

select id, array_agg(array[x,y]) from the_table group by id; 

Note that the default text representation of arrays uses curly braces ( {..}) not square brackets ([..])

like image 52
a_horse_with_no_name Avatar answered Sep 19 '22 17:09

a_horse_with_no_name