如何将 AVG 与计数一起使用

How to use AVG with Count

我有问题,我需要对居住在城市的人进行平均。在数据库中,我可以找到这样的活人数量

  SELECT CityName, (SELECT COUNT(*) from People where City.miestoID = 
    People.miestoID) as LivingPeople from City

并得到这个 http://prntscr.com/p5dbin

现在我需要对城市中的活人进行平均。我试试

  SELECT CityName, (SELECT AVG(COUNT(*) from People where City.miestoID = 
    People.miestoID)) as LivingPeople from City

我正在使用 SSMS。我找不到任何解决方案,但我知道我做错了什么。

我会做:

select avg(LivingPeople)
from (
  select count(p.miestoID) as LivingPeople
  from City c
  left join People p on p.miestoID = c.miestoID
) x

如果你想从你的查询中取平均值,那么你必须像下面那样尝试

select avg(LivingPeople) from 
(SELECT CityName ,(SELECT COUNT(*) from People where City.miestoID = 
People.miestoID) as LivingPeople from City
) a

假设所有城市至少有一个人,你可以这样做:

select count(*) * 1.0 / count(distinct miestoID);
from people;

* 1.0是因为SQL服务器做整数除法。

人口数除以城市数。