I have a table of polygons with a column 'class'. In that column are 25 different categories; however, I am only concerned with three polygon classes: marsh, water, and grass. I would like to extract only those polygons that touch each other among those three classes. I'm looking for continuous areas from the water, marsh, and grass areas only. I have an illustration of a test data set (water = blue, marsh = green, grass = yellow).
The following sql code is a step forward, but it doesn't work for three classes only two. It also doesn't select some of the elements:
DROP TABLE IF EXISTS adj;
CREATE TABLE adj AS
WITH m1 AS (
SELECT a.fid, a.class, (ST_Dump(ST_Union(a.geom, b.geom))).geom
FROM test as a,
test as b
WHERE a.fid < b.fid
AND ST_Touches(a.geom, b.geom)
AND a.class = 'MARSH'
AND b.class = 'WATER'
GROUP BY a.fid, a.class, a.geom, b.geom
)
SELECT * FROM m1;

ST_Touches- as in those geometries may not share their interiors - or is at least touches what you are looking for, i.e.ST_Intersects? If the latter, you want to useST_ClusterDBSCANwitheps := 0. – geozelot Dec 15 '23 at 17:19AtouchesBtouchesC, current code would createABand alsoBC), and you would have to include all classesAND a.class in ( 'MARSH', 'water','grass') and b.class in ( 'MARSH', 'water','grass'). But reallyst_clusterDBScanis the way to go – JGH Dec 15 '23 at 19:00