Skip to content

Instantly share code, notes, and snippets.

@dbauszus-glx
Created April 20, 2018 17:21
Show Gist options
  • Save dbauszus-glx/d5a9f58688cc1b612917a1e1a7cd2ab2 to your computer and use it in GitHub Desktop.
Save dbauszus-glx/d5a9f58688cc1b612917a1e1a7cd2ab2 to your computer and use it in GitHub Desktop.
KMeans DBScan nested group by to json.
SELECT
SUM(count)::integer count,
JSON_Agg(JSON_Build_Object(cat, count)) cat,
ST_AsGeoJson(ST_PointOnSurface(ST_Union(geom))) geomj
FROM (
SELECT
COUNT(cat) count,
ST_Union(geom) geom,
cat,
kmeans_cid,
dbscan_cid
FROM (
SELECT
cat,
kmeans_cid,
geom AS geom,
ST_ClusterDBSCAN(geom, 0.1, 1) OVER (PARTITION BY kmeans_cid) dbscan_cid
FROM (
SELECT
brand AS cat,
ST_ClusterKMeans(geom, 10) OVER () kmeans_cid,
geom
FROM gb_retailpoint
) kmeans
) dbscan GROUP BY kmeans_cid, dbscan_cid, cat
) cluster GROUP BY kmeans_cid, dbscan_cid;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment