Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Group by and concatenate arrays in PostgreSQL

I have a table in PostgreSQL. I want to concatenate all the arrays(i.e. col) after grouping them by time. The arrays are of varying dimensions.

| time  | col               |
|------ |------------------ |
| 1     | {1,2}             |
| 1     | {3,4,5,6}         |
| 2     | {}                |
| 2     | {7}               |
| 2     | {8,9,10}          |
| 3     | {11,12,13,14,15}  |

The result should be as follows:

| time  | col               |
|------ |------------------ |
| 1     | {1,2,3,4,5,6}     |
| 2     | {7,8,9,10}        |
| 3     | {11,12,13,14,15}  |

What I have come up with so far is as follows:

SELECT ARRAY(SELECT elem FROM tab, unnest(col) elem);

But this does not do the grouping. It just takes the entire table and concatenates it.

like image 915
mrtyormaa Avatar asked Jun 29 '18 12:06

mrtyormaa


People also ask

How does group by work in PostgreSQL?

The PostgreSQL GROUP BY clause is used in collaboration with the SELECT statement to group together those rows in a table that have identical data. This is done to eliminate redundancy in the output and/or compute aggregates that apply to these groups.

What is [] in PostgreSQL?

Array Type. PostgreSQL gives the opportunity to define a column of a table as a variable length single or multidimensional array. Arrays of any built-in or user-defined base type, enum type, or composite type can be created. We will focus on one data type in particular, the Array of text, text[].

What is Unnest in PostgreSQL?

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. PostgreSQL offers unnest() function.

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

To preserve the same dimension of you array you can't directly use array_agg(), so first we unnest your arrays and apply distinct to remove duplicates (1). In outer query this is the time to aggregate. To preserve values ordering include order by within aggregate function:

select time, array_agg(col order by col) as col
from (
  select distinct time, unnest(col) as col
  from yourtable
) t
group by time
order by time

(1) If you don't need duplicate removal just remove distinct word.

like image 187
Kamil Gosciminski Avatar answered Sep 25 '22 22:09

Kamil Gosciminski