This example loads a CartoDB layer using a crazy SQL from a small variation of this awesome Stack Overflow response. Note the use of CSS style tags for the CartoCSS to allow easy editing.
The uncompressed (and not perfect!) version of the SQL to draw the Voronoi diagram is:
WITH
Sample AS (
SELECT st_setsrid(st_union(the_geom),0) as geom
FROM registro_centros_nz WHERE spanish = 1
),
Edges AS (
SELECT id,
UNNEST(ARRAY['e1','e2','e3']) EdgeName,
UNNEST(ARRAY[
ST_MakeLine(p1,p2) ,
ST_MakeLine(p2,p3) ,
ST_MakeLine(p3,p1)]) Edge,
ST_Centroid(ST_ConvexHull(ST_Union(
ST_CurveToLine(REPLACE(
ST_AsText(ST_LineMerge(ST_Union(ST_MakeLine(p1,p2),ST_MakeLine(p2,p3)))),
'LINE','CIRCULAR'),15),
ST_CurveToLine(REPLACE(
ST_AsText(ST_LineMerge(ST_Union(ST_MakeLine(p2,p3),ST_MakeLine(p3,p1)))),
'LINE','CIRCULAR'),15)
))) ct
FROM (
SELECT id,
ST_PointN(g,1) p1,
ST_PointN(g,2) p2,
ST_PointN(g,3) p3
FROM (
SELECT (gd).Path id, ST_ExteriorRing((gd).Geom) g
FROM (SELECT (ST_Dump(ST_DelaunayTriangles(geom))) gd FROM Sample) a
)b
) c
),
Voronoi AS(
SELECT *
FROM (
SELECT
ST_LineMerge(ST_Union(ST_MakeLine(
x.ct,
CASE
WHEN y.id IS NULL THEN
CASE WHEN ST_Within(
x.ct, (SELECT ST_ConvexHull(geom) FROM sample))
THEN
ST_MakePoint(
ST_X(x.ct) + ((ST_X(ST_Centroid(x.edge)) - ST_X(x.ct)) * 2),
ST_Y(x.ct) + ((ST_Y(ST_Centroid(x.edge)) - ST_Y(x.ct)) * 2))
END
ELSE
y.ct
END
))) v
FROM Edges x
LEFT OUTER JOIN
Edges y ON x.id <> y.id AND ST_Equals(x.edge,y.edge)
) z
),
Convex as (
SELECT
ST_Buffer(
ST_ConvexHull(
ST_Transform(
ST_SetSrid(sample.geom,4326)
,3857)
)
,20) as geom
FROM sample
)
SELECT
int4(row_number() OVER (ORDER BY v)) AS cartodb_id,
ST_Intersection(
convex.geom,
ST_Transform(ST_SetSRID(v,4326),3857)
) AS the_geom_webmercator
FROM voronoi,convex