Last active
August 29, 2022 18:08
-
-
Save pramsey/87f8d7cb0633282c37e5 to your computer and use it in GitHub Desktop.
Convert a Linestring into a set of two-point segments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| CREATE TABLE lines ( | |
| gid integer primary key, | |
| geom geometry(Linestring, 4326) | |
| ); | |
| INSERT INTO lines VALUES (1, 'SRID=4326;LINESTRING(1 1, 2 2, 3 3, 4 4)'); | |
| INSERT INTO lines VALUES (2, 'SRID=4326;LINESTRING(0 1, 0 2, 0 3, 0 4)'); | |
| WITH | |
| dumps AS ( | |
| SELECT gid, ST_DumpPoints(geom) AS pt FROM lines | |
| ), | |
| pts AS ( | |
| SELECT gid, (pt).geom, (pt).path[1] AS vert FROM dumps | |
| ) | |
| SELECT a.gid, ST_AsText(ST_MakeLine(ARRAY[a.geom, b.geom])) AS geom, | |
| a.vert, b.vert | |
| FROM pts a, pts b | |
| WHERE a.gid = b.gid AND a.vert = b.vert-1 AND b.vert > 1; | |
| -- High performance alternative | |
| WITH segments AS ( | |
| SELECT gid, ST_AsText(ST_MakeLine(lag((pt).geom, 1, NULL) OVER (PARTITION BY gid ORDER BY gid, (pt).path), (pt).geom)) AS geom | |
| FROM (SELECT gid, ST_DumpPoints(geom) AS pt FROM lines) as dumps | |
| ) | |
| SELECT * FROM segments WHERE geom IS NOT NULL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What about using DumpPoints result into ST_Split function? See my fork https://gist.github.com/caiohamamura/d53c77887df137159d800701adc7cdf2