2016-02-18 67 views
7

POSTGIS集群我想计算点的集群,并为每个簇得到特定属性的(比如说让,每个点的集群中的得分之和)的总和与其他聚合

我已经设法使用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,我得到的分数的总和的所有位置,这是不是我想要(我想要在群集中的位置的总和)

+0

尝试用另一种选择包木窗它,并通过在外部做组选择.... SELECT总和,产业集群的(您的查询)组由集群 – sagi

+0

不能让它工作。为了总结我的外部查询,我需要在我的内部查询中对分数属性进行分组或汇总(因为ST_Clusterwithin已经是一个聚合函数) – Chris

回答

3

这是一个棘手的一个和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_CollectionHomogenizeST_CollectionExtract(<geometrycollection>, 1)(选择多边形1为点,2的线串和3)如建议在这个答案: https://gis.stackexchange.com/questions/195915/ 因为这个错误:https://trac.osgeo.org/postgis/ticket/3569

不要问我,你为什么不能做ST_Contains(<geometrycollection>, <geometry>); 我们需要转换为允许作为参数的多点。

元:这个问题本来是一个伟大的比赛为https://gis.stackexchange.com/

+0

很好的答案,谢谢 – Chris

+0

如果是“FROM locations”而不是“ FROM位置“,在外部选择? – Vesanto

+0

@Vesanto谢谢,更新! – EoghanM

0

在PostGIS 2.3,一个可能会从ST_ClusterDBSCAN功能(第三个参数的选择,它减少了层次聚类)直接返回相应的集群中获利指数:

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