StellaMaris
StellaMaris

Reputation: 867

Postgres overlap arrays from one column

I have a Table "A" with one column "col1" where each record is a array of integers.

col1
-----
{1,2,3,4}
{1,2,6,7}
{1,2,3,8,9}

I like to have one row as result which contains the overlap or intersect of all arrays in "col1".

select overlap(col1) from A;

result
-----
{1,2}

Upvotes: 2

Views: 1026

Answers (1)

Pavel Stehule
Pavel Stehule

Reputation: 45770

You should to define custom aggregate for this purpose:

CREATE OR REPLACE FUNCTION public.overlap_array_aggregate(anyarray, anyarray)
 RETURNS anyarray
 LANGUAGE plpgsql STRICT
AS $function$
BEGIN
  RETURN ARRAY(SELECT unnest($1) INTERSECT SELECT unnest($2));
END;
$function$

CREATE AGGREGATE array_overlap_agg (
   basetype = anyarray,
   sfunc =  overlap_array_aggregate,
   stype = anyarray );

Then it is working as you expect:

postgres=# SELECT * FROM foo;
┌─────────────┐
│      a      │
╞═════════════╡
│ {1,2,3,4}   │
│ {1,2,6,7}   │
│ {1,2,3,8,9} │
└─────────────┘
(3 rows)

postgres=# SELECT array_overlap_agg(a) FROM foo;
┌───────────────────┐
│ array_overlap_agg │
╞═══════════════════╡
│ {1,2}             │
└───────────────────┘
(1 row)

Upvotes: 8

Related Questions