我有一个表"A",其中一列"col1",其中每个记录是一个整数数组.
col1
-----
{1,2,3,4}
{1,2,6,7}
{1,2,3,8,9}
Run Code Online (Sandbox Code Playgroud)
我喜欢有一行结果,其中包含"col1"中所有数组的重叠或交叉.
select overlap(col1) from A;
result
-----
{1,2}
Run Code Online (Sandbox Code Playgroud)
您应该为此目的定义自定义聚合:
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 );
Run Code Online (Sandbox Code Playgroud)
然后它按预期工作:
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)
Run Code Online (Sandbox Code Playgroud)