Search code examples
postgresqlaggregate-functions

Postgresql array unique aggregation


I have a large table with structure

CREATE TABLE t (
  id SERIAL primary key ,
  a_list int[] not null,
  b_list int[] not null,
  c_list int[] not null,
  d_list int[] not null,
  type int not null 
)

I want query all unique values from a_list, b_list, c_list, d_list for type like this

    select 
        some_array_unique_agg_function(a_list), 
        some_array_unique_agg_function(b_list), 
        some_array_unique_agg_function(c_list), 
        some_array_unique_agg_function(d_list),
        count(1) 
    where type = 30

For example, for this data

+----+---------+--------+--------+---------+------+
| id | a_list  | b_list | c_list | d_list  | type |
+----+---------+--------+--------+---------+------+  
| 1  | {1,3,4} | {2,4}  | {1,1}  | {2,4,5} | 30   |
| 1  | {1,2,4} | {2,4}  | {4,1}  | {2,4,5} | 30   |
| 1  | {1,3,5} | {2}    | {}     | {2,4,5} | 30   |
+----+---------+--------+--------+---------+------+

I want the next result

+-------------+--------+--------+-----------+-------+
| a_list      | b_list | c_list | d_list    | count |
+-------------+--------+--------+-----------+-------+  
| {1,2,3,4,5} | {2,4}  | {1,4}  | {2,4,5}   | 3     |
+-------------+--------+--------+-----------+-------+

Is there some_array_unique_agg_function for my purposes?


Solution

  • Try this

    with cte as (select 
            unnest( a_list::text[] )::integer as a_list, 
            unnest( b_list::text[] )::integer as b_list, 
            unnest( c_list::text[] )::integer as c_list, 
            unnest( d_list::text[] )::integer as d_list,
            (select count(type) from t) as type
        from t 
        where type = 30
    )
    select array_agg(distinct a_list),array_agg(distinct b_list)
    ,array_agg(distinct c_list),array_agg(distinct d_list),type from cte group by type ;
    

    Result:

    "{1,2,3,4,5}";"{2,4,NULL}";"{1,4,NULL}";"{2,4,5}";3