Since we have written the query as a function, the query uses the SELECT statement to loop through all available records and give us a proportioned population. Astute readers will note that we have not yet done any work on summarization; we have only worked on the proportionality portion of the problem. We can do the summarization upon calling the function using PostgreSQL's built-in aggregate functions. What is neat about this approach is that we need not just apply a sum, but we could also calculate other aggregates such as min or max. In the following example, we will just apply a sum:
SELECT ROUND(SUM(chp02.proportional_sum(a.the_geom, b.the_geom, b.pop))) FROM chp02.trail_buffer AS a, chp02.trail_census as b WHERE ST_Intersects(a.the_geom, b.the_geom) GROUP BY a.gid;
The value returned is quite different (a population of 96,081), which is more likely to be accurate.