我通过连接wkt并将GEOMETRYCOLLECTION
与STUFF
结合使用,来强制ORDER BY
中包含几何图形的顺序
(我正在使用SQL Server 2016,否则我将使用STRING_AGG)
DECLARE @OrderedGeometryList TABLE
(
[GroupId] INT,
[Geometry] GEOMETRY,
[Order] INT
)
INSERT @OrderedGeometryList
VALUES
(1, 'LINESTRING(3 3, 4 4)', 3)
,(1, 'LINESTRING(0 0, 1 1)', 1)
,(1, 'LINESTRING(1 1, 2 2)', 2)
,(2, 'POINT(35453 141)', 2)
,(2, 'MULTILINESTRING((0 0, 1 1),(2 2, 3 3))', 1)
然后
;WITH Grouped AS (
SELECT
[GroupId]
,Geometry::STGeomCollFromText(
'GEOMETRYCOLLECTION(' +
STUFF((
SELECT ',' + [Geometry].ToString()
FROM @OrderedGeometryList t2
WHERE t1.[GroupId] = t2.[GroupId]
ORDER BY [Order]
FOR XML PATH ('')
), 1, 1, '')
+ ')', MAX([Geometry].STSrid)
) as [Geometry]
FROM @OrderedGeometryList t1
GROUP BY [GroupId]
)
SELECT GroupId, Geometry.ToString() as WKT
FROM Grouped
产生:
GroupId WKT
1 GEOMETRYCOLLECTION (LINESTRING (0 0, 1 1), LINESTRING (1 1, 2 2), LINESTRING (3 3, 4 4))
2 GEOMETRYCOLLECTION (MULTILINESTRING ((0 0, 1 1), (2 2, 3 3)), POINT (35453 141))
请注意收集顺序(从左到右)如何遵循表中指定的顺序。这是我所追求的效果,但是我很好奇是否有更干净的方法可以做到这一点。
我考虑编写自己的CLR聚合,然后将OVER()
与ORDER BY
一起使用,但似乎Is it possible to use user defined aggregates (clr) with window functions (over)?不支持此操作
答案 0 :(得分:2)
您可以在子查询中使用OFFSET
对行进行排序。
SELECT Geometry::CollectionAggregate([Geometry]).ToString()
FROM
(SELECT * FROM @OrderedGeometryList ORDER BY [GroupId], [Order] OFFSET 0 ROWS) T
GROUP BY [GroupId]
结果:
GEOMETRYCOLLECTION (LINESTRING (0 0, 1 1), LINESTRING (1 1, 2 2), LINESTRING (3 3, 4 4))
GEOMETRYCOLLECTION (MULTILINESTRING ((0 0, 1 1), (2 2, 3 3)), POINT (35453 141))