Evo peti:
WITH tablica AS
(SELECT muny.name_2 as opcina, roads.gid as roadsgid, railways.gid as railwaysgid, pois.name as bolnica,
ROUND( ST_Distance(pois.geom, ST_Intersection(roads.geom, railways.geom)) ) AS distance,
rank() OVER (PARTITION BY roads.gid, railways.gid
ORDER BY ROUND( ST_Distance(pois.geom, ST_Intersection(roads.geom, railways.geom)) )) AS rang
FROM muny, roads, railways, pois
WHERE muny.name_1 = 'Splitsko-Dalmatinska'
AND ST_Intersects(railways.geom, muny.geom)
AND ST_Intersects(roads.geom, railways.geom)
AND ST_Intersects(ST_Intersection(roads.geom, railways.geom), muny.geom)
AND pois.fclass = 'hospital'
)
SELECT opcina, roadsgid, railwaysgid, bolnica, MIN(distance)
FROM tablica
WHERE rang = 1
GROUP BY opcina, roadsgid, railwaysgid, bolnica
ORDER BY opcina, roadsgid, railwaysgid, bolnica