如何将线串拆分成各自的线段?

How to split linestrings into their individual segments?

我是 PostGIS 新手。我有一组(数千个)线串和沿线关联的多个点。我想将每条线分成一组仅由 2 个点组成的线段。我找到了一些答案,但是 none 我想要的答案。例如 https://gis.stackexchange.com/questions/21648/explode-multilinestring-into-individual-segments-in-postgis-1-5

我的问题:

只需转储大 LineString 的点,然后使用 ST_MakeLine 和单个点创建小点,然后使用 window 函数 LEAD() 创建序列中的下一个点。最后使用 ST_Collect:

创建一个带有小 LineStrings 的 MultiLinestring
WITH j AS (
  SELECT gid, ST_MakeLine(j.geom,LEAD(j.geom) OVER w) AS line
  FROM t, ST_DumpPoints(geom) j (path,geom)
  WINDOW w AS (PARTITION BY gid ORDER BY j.path
               ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING)
)
SELECT ST_Collect(line) FROM j
GROUP BY gid;

演示:db<>fiddle

CREATE TABLE t (gid int, geom geometry(linestring,4326));
INSERT INTO t VALUES 
(1,'LINESTRING(1 1,2 2,3 3,4 4)'),
(2,'LINESTRING(3 3,7 7,4 4)'),
(3,'LINESTRING(5 5,6 6)');


WITH j AS (
  SELECT gid, ST_MakeLine(j.geom,LEAD(j.geom) OVER w) AS line
  FROM t, ST_DumpPoints(geom) j (path,geom)
  WINDOW w AS (PARTITION BY gid ORDER BY j.path
               ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING)
)
SELECT ST_AsText(ST_Collect(line)) FROM j
GROUP BY gid;
                   st_astext                    
------------------------------------------------
 MULTILINESTRING((1 1,2 2),(2 2,3 3),(3 3,4 4))
 MULTILINESTRING((3 3,7 7),(7 7,4 4))
 MULTILINESTRING((5 5,6 6))
(3 rows)