I have a view defined as:
CREATE VIEW View1 AS
SELECT Field1, Field2, array_agg(Field3) AS AggField
FROM Table1
GROUP BY Field1, Field2;
What I would like to do is get the intersection of the arrays in AggField with something like:
SELECT intersection(AggField) FROM View1 WHERE Field2 = 'SomeValue';
Is this at all possible, or is there a better way to achieve what I want?
The closest thing to an array intersection that I can think of is this:
This assumes that
a1anda2are single dimension arrays with the same type of elements. You could wrap that up in a function something like this:Then you could do things like this:
Note that this doesn’t guarantee any particular order in the returned array but you can fix that if you care about it. Then you could create your own aggregate function:
And now we see why
array_intersectdoes funny and somewhat kludgey things with NULLs. We need an initial value for the aggregation that behaves like the universal set and we can use NULL for that (yes, this smells a bit off but I can’t think of anything better off the top of my head).Once all this is in place, you can do things like this:
Not exactly simple or efficient but maybe a reasonable starting point and better than nothing at all.
Useful references:
array_aggunnest