计算postgresql缓冲区内多边形的百分比

时间:2021-06-08 18:45:24

标签: sql postgresql geospatial postgis spatial-query

我有一个名为 Operation 的表,其中有多个点作为 geom,我创建了一个 100m 的缓冲区并作为新列添加到同一个表中。我有另一个名为 Residential 的表,它有多个多边形,目标是找到每个缓冲区内多边形的百分比,并将其添加为操作表中的一列。我不知道如何继续。

SELECT AddGeometryColumn ('public','operations','buffer',4326,'POLYGON',2);
UPDATE operations SET buffer = ST_Buffer(geom::geography,100)::geometry;

ALTER TABLE operations ADD COLUMN pts int;

UPDATE operations o 
SET pts = (SELECT count(*) FROM supermarket s
           WHERE ST_Contains(o.buffer,s.geom));

我已经这样做了,以下几行不适合获取百分比。如何解决这个问题。

    ALTER TABLE public."Operation" ADD COLUMN res_percent double precision;
UPDATE public."Operation"  
SELECT      
  ST_Intersection(ST_MakeValid(r.geom),o.buffer) AS intersection,   
  ST_Area(ST_Intersection(ST_MakeValid(r.geom),o.buffer))/ST_Area(r.geom)*100)) 
FROM public."Residential" r, public."Operation" o 
WHERE ST_Intersects(o.buffer,ST_MakeValid(r.geom));

dbfiddle

1 个答案:

答案 0 :(得分:2)

使用ST_Area获得多边形的面积,使用ST_Intersection提取它们的交集面积,然后最后使用交集面积和多边形面积计算重叠比例。

示例

给定两个重叠的多边形,p1p2,位于名为 t 的表中:

enter image description here

我们可以使用 ST_Intersection 得到两个多边形的交集:

SELECT ST_Intersection(p1,p2) FROM t;

enter image description here

现在我们可以使用 ST_Area 来计算这个交叉点的面积:

SELECT ST_Area(ST_Intersection(p1,p2)) FROM t;

    st_area     
----------------
 601950.9523732
(1 row)

因此,在交集和多边形中使用 ST_Area,您可以计算一个多边形与另一个多边形重叠的百分比,例如

SELECT 
  ST_Area(ST_Intersection(p1,p2))/ST_Area(p2)*100 AS perc_p2, 
  ST_Area(ST_Intersection(p1,p2))/ST_Area(p1)*100 AS perc_p1
FROM t;

     perc_p2      |     perc_p1      
------------------+------------------
 30.0839473794556 | 37.9061430278047
(1 row)

演示:db<>fiddle

根据您的描述,您的查询应该看起来像这样:

SELECT   
  ST_Intersection(r.geom,o.buffer) AS intersection,
  ST_Area(ST_Intersection(r.geom,o.buffer))/ST_Area(r.geom)*100
FROM residential r, operations o
WHERE ST_Intersects(o.buffer,r.geom);
相关问题