【问题标题】:How to use sum in a where clause to calculate a avg如何在 where 子句中使用 sum 来计算平均值
【发布时间】:2012-11-05 18:28:43
【问题描述】:

我还是 sql 新手,我刚刚使用 postgresql 一个星期。我有点卡住了..

我正在使用 NY 数据集 (http://workshops.opengeo.org/postgis-intro/about_data.html)。

我必须找到一种方法列出所有亚裔人口超过相应行政区平均水平的社区,并且我必须显示亚裔人口的百分比。

我想过这个:

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) 

但是我显然不会在 where 子句之后使用 sum...我想知道为什么并学习如何解决这个问题。

谢谢

【问题讨论】:

  • 这个怎么样?

标签: postgresql postgis average


【解决方案1】:
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) 

【讨论】:

  • 它不起作用。它说,轻描淡写的结果不能超过一个。 select avg(popn_asian) from nyc_census_blocks c1 group by c1.boroname (它不是白色的,而是亚洲的,但不会改变任何东西)。我想这是问题所在, avg(popn_asian) 必须高于该社区所在行政区的平均值,所以我想我需要添加类似 c1.boroname = n.boroname 之类的内容,但这也不起作用...
【解决方案2】:

您需要使用having 子句来解决此问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    • 2014-10-10
    • 2011-07-13
    • 1970-01-01
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多