2013-10-13 124 views
1

所以我有查詢:SQL從計數中找到平均值?

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 

);

+0

你可以發佈你的表結構? –

+0

每個州有多少個國家?不是每個國家有多少個州? – Lion

回答

2

這可能是它的數量的平均值?

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 
0

如果我不缺什麼,這應該基本上是給你同樣的結果在其他的答案雙重分組方法:

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