24

I've got a simple problem: I want to count the number of points within a set of polygons.

I have a SQL already but it only gives back the gid of the polygone that actually contains points.

My tables: a polygon layer with 19.000 rows and a point layer with 450 rows.

The following SQL-query

SELECT grid.gid, count(*) AS totale
FROM grid, kioskdhd3
WHERE st_contains(grid.geom,kioskdhd3.geom)
GROUP BY grid.gid;

returns only some 320 polygons that actually contain points. But I want all polygons returned, even thought the number of points is 0.

Of course it has to do with my WHERE-clause. Where do I have to put in my st_contains()?

Taras
  • 32,823
  • 4
  • 66
  • 137
hoge6b01
  • 1,118
  • 3
  • 20
  • 39
  • see http://gis.stackexchange.com/questions/42951/how-fill-length-and-feature-count-in-postgis-table-for-each-polygons – spatialhast Mar 16 '13 at 13:23
  • thanks, but they all have a WHERE-clause. I don't know if I need one. How would you re-write it? – hoge6b01 Mar 16 '13 at 13:56

2 Answers2

33
SELECT grid.gid, count(kioskdhd3.geom) AS totale 
FROM grid
LEFT JOIN kioskdhd3 ON st_contains(grid.geom,kioskdhd3.geom)
GROUP BY grid.gid;
Taras
  • 32,823
  • 4
  • 66
  • 137
Nicklas Avén
  • 13,241
  • 1
  • 39
  • 48
-1

Per this left joins are not supported in GiST indices.

May I recommend:

SELECT grid.gid, 
       SUM(CASE WHEN st_contains(grid.geom,kioskdhd3.geom) THEN 1 ELSE 0 END) AS total
FROM grid, kioskdhd3 
GROUP BY grid.gid;
raphael
  • 3,407
  • 23
  • 61
  • 2
    The querry does not utilize spatial indexes: http://explain.depesz.com/s/U6Iy. Nicklas answer does : http://explain.depesz.com/s/nhH – nickves Mar 13 '15 at 08:49