Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres GROUP BY Array Column

I use postgres & have a table like this :

id   | arr
-------------------
 1   | [A,B,C]
 2   | [C,B,A]
 3   | [A,A,B]
 4   | [B,A,B]

I created a GROUP BY 'arr' query.

SELECT COUNT(*) AS total, "arr" FROM "table" GROUP BY "arr"

... and the result :

total | arr
-------------------
 1    | [A,B,C]
 1    | [C,B,A]
 1    | [A,A,B]
 1    | [B,A,B]

BUT, since [A,B,C] and [C,B,A] have the same elements, so i expected the result should be like this :

total | arr
-------------------
  2   |   [A,B,C]
  2   |   [A,A,B]

Did i miss something (in query) or else? Please help me..

like image 537
Raditya Arya Avatar asked Jun 03 '18 07:06

Raditya Arya


People also ask

What is the use of group by in PostgreSQL?

PostgreSQL - GROUP BY. 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 the difference between group_concat and array_agg in PostgreSQL?

Instead of using group_concat in PostgreSQL we are using array_to_string and array_agg function. Array_agg function is basically used to retrieve element of array from the table. Using this function we are retrieving the column array elements value.

What is a PostgreSQL array?

PostgreSQL allows columns of a table to be defined as variable-length multidimensional arrays. Arrays of any built-in or user-defined base type, enum type, or composite type can be created.

How to get the name of a column in PostgreSQL?

Name of column: This is defined as select the name of column from the table to retrieve and concatenate the data of column by using the array_to_string and array_agg function in PostgreSQL. Array_to_string: This function in PostgreSQL works same as group_concat function which was used in other database.


1 Answers

You do not need to create a separate function to do this. It can all be done in a single statement:

select array(select unnest(arr) order by 1) as sorted_arr, count(*)
from t
group by sorted_arr;

Here is a rextester.

like image 68
Gordon Linoff Avatar answered Oct 02 '22 09:10

Gordon Linoff