Click here to Skip to main content
15,895,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
i have two tables: states and cities

states
----------
 - stateid
 - statename

cities
--------
 - cityid
 - cityname
 - stateid

i want display statename with no of cities in that state

statename    count(cities)
---------    -----
keral          5
chennai        10

Can any one tell me the sql query to get the result?
Posted
Updated 25-May-12 0:30am
v2

Like this:
SQL
SELECT s.statename, COUNT(c.cityid) AS CountOfCities
FROM cities as c LEFT JOIN states as s ON c.stateid = s.stateid
GROUP BY s.statename


As Manfred R. Bihy wrote in comment, if you would like to get all states and cities, even if state has no city - probably it's impossible ;) - you need to use query like this:
SQL
SELECT s.statename, COUNT(c.cityid) AS CountOfCities
FROM states as s LEFT JOIN cities as c ON s.stateid = c.stateid
GROUP BY s.statename


Thank you Manfred ;)
 
Share this answer
 
v3
Comments
Manfred Rudolf Bihy 25-May-12 6:44am    
I'm not sure if this is a requirement, but if there is a state that does not have any cities associated with it, it will not show up with a city count of zero. That is why I chose to join the tables the other way. Anyhow, take a 5. OP did not state any specific requirement.

:)
Maciej Los 25-May-12 6:46am    
I agree with you ;)
Thank you :)
Manfred Rudolf Bihy 25-May-12 7:42am    
You're welcome. Actually before I had seen your solution I had used an inner join and your left join got me thinking of the consequences. So you did indeed help me too. :)
Thanks for that!
Srinivas Kumar Pasumarthi 25-May-12 6:57am    
its working properly meets my requirement
Maciej Los 25-May-12 7:08am    
OK, thank you for the information ;)
Please try the following SQL statement:

SQL
SELECT st.StateName, COUNT(cy.cityid) as NoOfCities
FROM states st LEFT JOIN cities cy ON st.StateId == cy.StateId
GROUP BY st.StateName


Regards,

Manfred
 
Share this answer
 
v5
Comments
Maciej Los 25-May-12 6:35am    
Good one, +5!
Manfred Rudolf Bihy 25-May-12 6:41am    
Thanks! :)
VJ Reddy 25-May-12 6:38am    
Good answer. 5!
Manfred Rudolf Bihy 25-May-12 6:41am    
Thanks VJ! :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900