PostGIS Polygons – How to Get Intersection of Polygons in the Same Table

postgispostgresqlpostgresql-9.6spatial-analystsql

I have a single table of over 1000 polygons in postgreSQL (with PostGIS), and I have a field "evaluation_type" that only receives two values, either 'good'(green) or 'bad'(red), as you can see in the picture below.

enter image description here
Once some 'bad' and 'good' polygons overlap, I'd like to use a PostGIS function where I can get the following:

3 feat

And in the attribute table I'd have
– 'good'
– 'bad'
– 'fair': For the intersections

I'd like the result layer (the one containing the intersection) in a "2D" layer, in other words, I want no overlap between the intersects. It's because, in the end, the thing I'm looking for is to count, for each small little polygon, how many 'good' and 'bad' polygons it represents, see below the hypothetical attribute table I want to have.

id| evaluation | count_good | count_bad

1 |  good    |   223    |   0 
2 |  fair    |   108    |   288 
3 |  bad     |   0      |   278 
4 |  fair    |   193    |   132 
5 |  fair    |   183    |   198
6 |  ...
  • If the small polygon only represents a intersection of 'good' polygons it will receive an value of 'good' and will have 0 in the field 'count_bad'
  • If the small polygon only represents a intersection of 'bad' polygons it will receive an value of 'bad' and will have 0 in the field 'count_good'
  • If the small polygon represents a intersection of 'bad' and 'good' polygons it will receive an value of 'fair' and will have 0 counts > 0 in both fields 'count_good' and 'count_bad'

As far as I remember in ArcGIS Union tool, it would break the intersections. I realized that ST_Union behaves a bit different. I used the following code and it returned a dissolved polygon.

    CREATE TABLE out_table AS  
    SELECT ST_Union(geom) as geom  
    FROM areas_demo;

Do you have a hint, how could I get such result I described?

Best Answer

you can use ST_INTERSECTION using the source table twice. Make sure to avoid comparing the a polygon to itself. Also avoid comparing a pair of polygon twice.

SELECT ST_INTERSECTION(a.geom, b.geom), 'fair'
FROM mytable a, mytable b
WHERE a.ID < b.ID
AND ST_INTERSECTS(a.geom, b.geom);
Related Question