Search code examples
sqlpostgresqlpostgis

Joining point value to polygon with With statements


I have loaded a function hex_grid, it works fine see here but now I have a hexagonal grid I would like to add up all the values from the overlapping centroid points from a polygon layer. I've used with statements to keep things a little tidy, both select statements work as expected, my problem occurs when joining, clearly I've done something wrong but I just can't see it, any help would be appreciated. Here's the code. The hex and points are both in the same crs.

with hex AS(
SELECT hex_grid(
1, 
(ST_XMIN(sa.geom)), 
(ST_YMIN(sa.geom)),
(ST_XMAX(sa.geom)),
(ST_YMAX(sa.geom)),
32635, 32635, 32635) as geom_h
FROM geodata.study_area sa),

points AS(
SELECT count(*) as count, ST_Centroid(su.geom) AS geom_p
FROM clas.survey_unit su
group by su.geom
)

SELECT hex.geom_h, points.count 
FROM hex     
JOIN points 
ON ST_Contains(points.geom_p, hex.geom_h)
group by hex.geom_h, points.count;

Solution

  • ST_Contains should have the polygon first, which contains the points

    ON ST_Contains(hex.geom_h,points.geom_p)