简体   繁体   中英

Too many observations returned by st_intersects

I'm trying to count the proportion of points that are meeting a certain condition in each polygon. I know how many observations in total are meeting the condition and I want to know how they are distributed among the polygons. However, the request I'm doing returns a total that is larger that the number I am supposed to have.

To do this I first have a table listing all points and a column which states if the condition is met (table2).

I also have a table with all the polygons (table1).

The two tables have the same geometry (3798).

I then used st_instersects(geom1,geom1) and count() in order to know how many points in each polygon.

I also tried st_within but the same problem happens.

SELECT table1.id, table1.name, count(table2.id) AS condition_met, table1.geom INTO newtable
FROM table1, table2
WHERE st_within(table1.geom, table2.geom) AND (table2.var = 4 OR table2.var = 5) 
GROUP BY table1.id, table1.name, table1.geom;

All requests are working but. I have a umber of observations for each polygon in which there are points that meet the condition. However, when I double-check the big total of observations, there is way too many observations than it is supposed.

This is the request I used to sum up the total number of observations in table1 (polygon):

SELECT SUM(condition_met) FROM table2.

I thought there were duplicates but didn't find any.

I'm pretty sure it is a simple mistake but I can't find it as I'm new to postgis.Thank you very much for your help!

I think your query as you have it tests if the polygon is within the point - you need to reverse the arguments, or use st_contains .. I would write your query like this:

SELECT table1.id, table1.name, count(table2.id) AS condition_met INTO newtable
FROM table1 
INNER JOIN table2 ON st_contains(table1.geom, table2.geom) -- I prefer join syntax
WHERE table2.var IN (4 ,5) -- IN is clearer 
GROUP BY table1.id, table1.name; -- leave out geom in the group by as it's slow

If you still get unexpected results it is possible that your polygons overlap as @JGH pointed out , so you double count some intersections. You can test that with a query like this, although you can check here for a more sophisticated query and discussion:

SELECT a.id, b.id FROM
table1 a
INNER JOIN
table1 b -- join to the same table
ON
ST_Overlaps(a.geom, b.geom) OR ST_Contains(a.geom, b.geom)
WHERE a.id <> b.id

If that query returns anything some polygons overlap.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM