【问题标题】:sql find average from counting?sql从计数中找到平均值?
【发布时间】:2013-10-13 22:25:50
【问题描述】:

所以我有疑问:

select states, count(numberofcounty) 
from countytable 
group by states  
order by count(distinct numberofcounty) ASC;

它返回一个包含 2 列的表:从最少到最多的州数和县数。 如何在单个实数中获得每个州有多少个县的平均值?

表结构为:

create table numberofcounty(
    numberofcounty text, 
    states text references states(states), 
);
create table states (
    states text primary key,  
    name text, 
    admitted_to_union text

);

【问题讨论】:

  • 你能发布你的表结构吗?
  • 每个州有多少个国家?不是每个国家有多少个州吗?

标签: sql count average


【解决方案1】:

可能是这个?

countytable:
state|county
a     aa
a     ab
a     ac
b     ba


SELECT AVG(counties) FROM (SELECT state, COUNT(county) as counties FROM countytable GROUP BY state) as temp

结果:2

【讨论】:

    【解决方案2】:

    您可以将当前查询用作获取每个州县数平均值的子查询

    Select avg (c) average_counties
    From (select count(numberofcounty) c
    from countytable 
    group by states) s
    

    【讨论】:

      【解决方案3】:

      如果我没有遗漏任何内容,这基本上应该会给您与其他答案中的双重分组方法相同的结果:

      SELECT COUNT(numberofcounty) / COUNT(DISTINCT states)
      FROM countytable
      ;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-19
        • 1970-01-01
        • 2021-02-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多