I want to select some points based on a intersection with a polygon coming from an other database as a WKT geometry.
For the moment, everything is working fine:
SELECT p.name, p.geom, p.class
FROM point_table p
WHERE ST_Intersects(
ST_Transform(p.geom, 2056),
ST_Transform(ST_GeomFromText('POLYGON(((6.12 46.22,...,6.12 46.22)))', 4326), 2056)
)
AND (...other conditions...);
But let's say the point have a 'class' attribute depicting the object they represent. When class='city' I not only want to select the point which are inside the polygon, but also those which are in a 1000m buffer and for class='Town' I'd like to apply a 500m buffer.
I can do this in two different ways; either buffering the polygon itself, or the points, where the class attribute of the points matches city
or town
using the appropriate distance for each.
As the polygon is quite large, I prefer to buffer the points themselves.
I was thinking of something like:
SELECT p.name, p.geom, p.class
FROM point_table p
WHERE
CASE
WHEN p.class = 'City'
THEN ST_Intersects(
ST_Buffer(ST_Transform(p.geom, 2056), 1000),
ST_Transform(ST_GeomFromText('POLYGON(((6.12 46.22,...,6.12 46.22)))', 4326), 2056)
)
WHEN p.class = 'Town'
THEN ST_Intersects(
ST_Buffer(ST_Transform(p.geom, 2056), 500),
ST_Transform(ST_GeomFromText('POLYGON(((6.12 46.22,...,6.12 46.22)))', 4326), 2056)
)
ELSE ST_Intersects(
ST_Transform(p.geom, 2056),
ST_Transform(ST_GeomFromText('POLYGON(((6.12 46.22,...,6.12 46.22)))', 4326), 2056)
)
END
AND (...other conditions...);
I think this actually works, but I'm wondering if there is a better approach?
For example, one which would not repeat the massive polygon 3x.
I always want to "pre-compute" the geometry in my SELECT
statement, using an alias, and then using this, but it's not interpreted in the rest of the query as if it doesn't exist at that moment, but only at the very end of the query:
SELECT p.name, p.geom, p.class,
CASE
WHEN p.class = 'City'
THEN ST_Buffer(ST_Transform(p.geom, 2056), 1000)
WHEN p.class = 'Town'
THEN ST_Buffer(ST_Transform(p.geom, 2056), 500)
ELSE p.geom
END new_geom --<---- That would be a nice solution, but I cannot use 'new_geom' hereafter.
FROM point_table p
WHERE ST_Intersects(
new_geom,
ST_Transform(ST_GeomFromText('POLYGON(((6.12 46.22,...,6.12 46.22)))', 4326), 2056)
)
AND (...other conditions...);
WITH
statement ? Have you looked at the ST_DWithin PostGIS function postgis.net/docs/ST_DWithin.html ?