I want to find one city for each state that has the maximum average population? I have three table state, city and population. The table provided are simplified, to only have 2 states
"state" Code is our key that is unquie for each state
name | code |
---|---|
Ohio | OH |
Wisconsin | WI |
"city"
two state codes to refer to border between two states
code | name |
---|---|
OH | Cevland |
OH | Dayton |
OH | Toledo |
WI | Madison |
WI | Racine |
"citypop"
code | name | Year | pop |
---|---|---|---|
OH | Cevland | 1998 | 10000 |
OH | Cevland | 2000 | 1000 |
OH | Dayton | 1998 | 6000 |
OH | Toledo | 1978 | 8000 |
WI | Madison | 1999 | 2000 |
WI | Madison | 2000 | 20000 |
WI | Racine | 2000 | 5000 |
Expected result : Cevland not choose because avgpop, madison and toledo are selected
city | avgpop |
---|---|
Toledo | 8000 |
Madison | 11000 |
The query i have made so far.
Select c.name, avg(cp.length)
from city c
Inner Join citypop cp
On c.name = cp.city
Group by c.name
My thinking is I want to select the name and avg, but not sure how to get the next step of only one city for each country.
'Edit' The reason its madison is because we add 2000, 20000 and then devide to get the average. so madision avg pop is 11000 and racine(having only one data point value) is 5000. We want the max average so we select madison.