与其他聚合的 PostGis 聚类
PostGis clustering with other aggregate
我想计算点簇,并为每个簇获得特定属性的总和(比如说,簇中每个点的分数总和)
我已经成功地使用 ST_ClusterWithin
构建了集群,但我无法计算总和。
这是我尝试过的:
SELECT sum(score), unnest(ST_ClusterWithin(coordinates, 0.1)) AS cluster
FROM locations
GROUP BY cluster;
但是我得到以下错误ERROR: aggregate functions are not allowed in GROUP BY
如果我删除 GROUP BY
,我会得到所有位置的分数总和,这不是我想要的(我想要集群中位置的总和)
这是一个棘手的问题,st_clusterwithin api 似乎没有针对常见情况设计得很好。
我能找到的唯一解决方案是重新加入集群,如下所示:
SELECT SUM(score), cluster FROM locations, (
SELECT unnest(ST_ClusterWithin(coordinates, 0.1)) AS cluster
FROM locations
) as location_clustered
WHERE ST_Contains(ST_CollectionExtract(cluster, 1), coordinates)
GROUP BY cluster;
编辑:我已按照建议将 ST_CollectionHomogenize
更改为 ST_CollectionExtract(<geometrycollection>, 1)
(选择 1
作为点,2
作为线串,3
作为多边形)在这个答案中:
https://gis.stackexchange.com/questions/195915/
因为这个错误:https://trac.osgeo.org/postgis/ticket/3569
别问我为什么做不到ST_Contains(<geometrycollection>, <geometry>)
;
我们需要转换为允许作为参数的多点。
Meta:这个问题非常适合 https://gis.stackexchange.com/
使用 PostGIS 2.3,可能会受益于 ST_ClusterDBSCAN 函数(第三个参数的选择将其简化为层次聚类),returns 直接对应的聚类索引:
WITH stat AS (
SELECT
score, ST_ClusterDBSCAN(coordinates, 0.1, 1) OVER () AS cluster_id
FROM
tmp_locations
)
SELECT
cluster_id, SUM(score)
FROM
stat
GROUP BY
cluster_id
ORDER BY
cluster_id
我想计算点簇,并为每个簇获得特定属性的总和(比如说,簇中每个点的分数总和)
我已经成功地使用 ST_ClusterWithin
构建了集群,但我无法计算总和。
这是我尝试过的:
SELECT sum(score), unnest(ST_ClusterWithin(coordinates, 0.1)) AS cluster
FROM locations
GROUP BY cluster;
但是我得到以下错误ERROR: aggregate functions are not allowed in GROUP BY
如果我删除 GROUP BY
,我会得到所有位置的分数总和,这不是我想要的(我想要集群中位置的总和)
这是一个棘手的问题,st_clusterwithin api 似乎没有针对常见情况设计得很好。
我能找到的唯一解决方案是重新加入集群,如下所示:
SELECT SUM(score), cluster FROM locations, (
SELECT unnest(ST_ClusterWithin(coordinates, 0.1)) AS cluster
FROM locations
) as location_clustered
WHERE ST_Contains(ST_CollectionExtract(cluster, 1), coordinates)
GROUP BY cluster;
编辑:我已按照建议将 ST_CollectionHomogenize
更改为 ST_CollectionExtract(<geometrycollection>, 1)
(选择 1
作为点,2
作为线串,3
作为多边形)在这个答案中:
https://gis.stackexchange.com/questions/195915/
因为这个错误:https://trac.osgeo.org/postgis/ticket/3569
别问我为什么做不到ST_Contains(<geometrycollection>, <geometry>)
;
我们需要转换为允许作为参数的多点。
Meta:这个问题非常适合 https://gis.stackexchange.com/
使用 PostGIS 2.3,可能会受益于 ST_ClusterDBSCAN 函数(第三个参数的选择将其简化为层次聚类),returns 直接对应的聚类索引:
WITH stat AS (
SELECT
score, ST_ClusterDBSCAN(coordinates, 0.1, 1) OVER () AS cluster_id
FROM
tmp_locations
)
SELECT
cluster_id, SUM(score)
FROM
stat
GROUP BY
cluster_id
ORDER BY
cluster_id