I have the following schema in PostgreSQL 12:
CREATE TABLE test_aggregate(
id_semilavorato text NOT NULL PRIMARY KEY,
array_allestimenti text[]
);
INSERT INTO test_aggregate VALUES ('A',ARRAY['IDA1','IDA2']);
INSERT INTO test_aggregate VALUES ('B',ARRAY['IDA1']);
INSERT INTO test_aggregate VALUES ('C',ARRAY['IDA2']);
INSERT INTO test_aggregate VALUES ('D',ARRAY['IDA3']);
INSERT INTO test_aggregate VALUES ('E',ARRAY['IDA4']);
I would like to create a query to obtain groups of semi-finished products and their respective common setups that share at least one element. In this case, that returns 3 records with 2 columns of type text[]
and text[]
, where each record contains semilavorati_comuni
(common semi-finished products) and allastimenti_comuni
(common setups).
The expected result would be:
semilavorati_comuni | allastimenti_comuni
{A,B,C} | {IDA1,IDA2}
{D} | {IDA3}
{E} | {IDA4}
How can I make this query?
2
Answers
id_semilavorato
in anarray[]
.allastimenti_comuni
overlap with&&
and checking if the other group isn’t already in it. To only get(A,B)
without also getting the symmetric(B,A)
pairing, only join higherid_semilavorato
to lower ones.allastimenti_comuni
arrays with||
and append the newid_semilavorato
ontosemilavorati_comuni
witharray_append()
.unnest()
closing back up witharray_agg(distinct e order by e)
.demo at db<>fiddle
With the additional set-based operators provided in
intarray
extension some of the logic here could be a bit simpler and faster if these were all integer identifiers .That could be achieved selecting first ids and its maximum common array, then the rest of ids with no common elements and finally grouping
Fiddle to test