WITH buf AS (
-- 2mi (3218.69m) point buffers
SELECT
ST_Collect(ST_Buffer(the_geom::geography, 3218.69)::geometry) AS the_geom
FROM sites
)
SELECT
c.*,
ST_Area(ST_Intersection(c.the_geom, buf.the_geom)::geography, true) /
ST_Area(c.the_geom::geography, true) AS pctwithin
FROM counties AS c, buf
First, it calculates the 2-mile buffers for all the sites, and collects them all into a single multi-polygon called buf
.
Then, for each county, it calculates the area of intersection with the buffers and divides it by the area of the whole county.
It returns the original county table with the addition of a single column called pctwithin
(which will be between 0.0 and 1.0, but you could multiply by 100 if you prefer).