I would like to use an aggregate version of the ST_Intersection function in PostGIS. In a table I have multiple polygons and would like to calculate the intersection of all of them. Ideally it would even be possible to group by one of the other columns. In short, I would like to use ST_Intersection as an aggregate function, or something similar to
SELECT groupid, ST_Intersection(geometry) FROM tablename GROUP BY groupid;
The result of this would be a table with a line for each groupid. The resulting geometry for each groupid should be the intersection of all polygons with this groupid.
Is there a way to do this in PostGIS?
Example:
My table contains four records, each containing a polygon. They are shown in the left column in the picture below. In the picture assume that the squares are every time the same square (e.g. [-1,1]x[-1,1]). Each of the records has a groupid, shown in text and with a color. In the output I want a record for each groupid. The polygon in the output should be the intersection of all input polygons from that group. In the picture they are shown in the right column.
In this pictures that means the record for groupid = 1 (green) should contain the intersection of all green input polygons and analogous for groupid = 2 (red). Here, the intersection of both green triangles is a smaller triangle and the intersection of the red rectangles is a smaller red square.
The example in code: The code for this example would look like this.
CREATE TEMPORARY TABLE simpleexample
(
id INT,
groupid INT,
polygon GEOMETRY
);
INSERT INTO simpleexample VALUES
(1, 1, ST_GeomFromText('POLYGON((-1 1, -1 -1, 1 -1, -1 1))')), -- lowerleft half of square [-1,1]x[-1,1]
(2, 1, ST_GeomFromText('POLYGON((1 1, -1 -1, 1 -1, 1 1))')), -- lowerright half of square [-1,1]x[-1,1]
(3, 2, ST_GeomFromText('POLYGON((-1 0, 1 0, 1 -1, -1 -1, -1 0))')), -- lower half of square [-1,1]x[-1,1]
(4, 2, ST_GeomFromText('POLYGON((0 1, 0 -1, 1 -1, 1 1, 0 1))')); -- left half of square [-1,1]x[-1,1]
-- making the intersections manually works fine
SELECT ST_AsText(ST_Intersection(ST_GeomFromText('POLYGON((-1 1, -1 -1, 1 -1, -1 1))'), ST_GeomFromText('POLYGON((1 1, -1 -1, 1 -1, 1 1))')));
-- correctly returns "POLYGON((1 -1,-1 -1,0 0,1 -1))"
SELECT ST_AsText(ST_Intersection(ST_GeomFromText('POLYGON((-1 0, 1 0, 1 -1, -1 -1, -1 0))'), ST_GeomFromText('POLYGON((0 1, 0 -1, 1 -1, 1 1, 0 1))')));
-- correctly returns "POLYGON((0 0,1 0,1 -1,0 -1,0 0))"
-- doing is all in one go doesn't work, this is what I would like to do
SELECT groupid, ST_Intersection(polygon) FROM simpleexample GROUP BY groupid
-- gives error "function st_intersection(geometry) does not exist"
-- I want this to be the two previously calculated lines in one table.
Obviously, I would have to do this for many more polygons than is handy for copy-pasting.

