Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use sum in a where clause to calculate an avg

I'm still new to SQL, I have just been using PostgreSQL for a week. I am a little stuck.

I'm using the NY dataset ( http://workshops.opengeo.org/postgis-intro/about_data.html ).

I have to find a way to list all the neighborhoods with more Asian population than the average of corresponding borough and I have to display the percentage of Asian population.

I thought about this:

select name, 100 * sum(c.popn_asian)/(select (avg(popn_asian)) from nyc_census_blocks group by boroname)
from nyc_neighborhoods n, nyc_census_blocks c
where (ST_Contains(n.geom, c.geom) = true )
and (sum(c.popn_asian)) > (select avg(popn_white) from nyc_census_blocks c1 group by c1.boroname) 

But I am not allowed to use sum after the where clause apparently... I'd like to know why and learn how to solve this problem.

Thanks

like image 727
Tsirkuse Avatar asked Jan 27 '26 09:01

Tsirkuse


1 Answers

select name, 100 * sum(c.popn_asian)/(select (avg(popn_asian)) from nyc_census_blocks group by boroname)
from nyc_neighborhoods n, nyc_census_blocks c
where ST_Contains(n.geom, c.geom) = true 
group by name
having sum(c.popn_asian) > (select avg(popn_white) from nyc_census_blocks c1 group by c1.boroname) 
like image 142
Alex Gordon Avatar answered Jan 30 '26 15:01

Alex Gordon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!