2

I have a database in PostgreSQL / PostGIS with polygons so how can i merge some polygons into multipolygons of the database using it as QGIS Layer?

2 Answers 2

4

You can use st_collect to aggregate polygons into multipolygons:

 with src as (
   select 1 as gp, st_geomFromText('Polygon((0 0, 0 1, 1 1, 1 0, 0 0))') geom 
   union 
   select 1, st_geomFromText('Polygon((10 10, 10 11, 11 11, 11 10, 10 10))') 
   union 
   select 2, st_geomFromText('Polygon((20 20, 20 21, 21 21, 21 20, 20 20))')
   )
 select gp, 
        st_asText(st_collect(geom)) 
 from src 
 group by gp;

 gp |                                st_astext
----+-------------------------------------------------------------------------
  1 | MULTIPOLYGON(((0 0,0 1,1 1,1 0,0 0)),((10 10,10 11,11 11,11 10,10 10)))
  2 | MULTIPOLYGON(((20 20,20 21,21 21,21 20,20 20)))
1

You can also use the function ST_Multi http://postgis.net/docs/ST_Multi.html

WITH src as (
   SELECT ST_GeomFromText('POLYGON((0 0, 0 1, 1 1, 1 0, 0 0),
                                   (10 10, 10 11, 11 11, 11 10, 10 10))') geom) 
   SELECT ST_AsText(ST_Multi(geom)) from src group by geom;

result:

MULTIPOLYGON(((0 0,0 1,1 1,1 0,0 0),(10 10,10 11,11 11,11 10,10 10)))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.