0

I have three table

State(stateid, statename)
District(dict_id,dict_name,stateid)
city(city_id,dict_id,city_name) 

I need to count Statename and cities in that state. Is it possible to get Statename, district_count, city_count in single query?

4

2 に答える 2

1

This should do:

SELECT  S.Statename, 
        COUNT(DISTINCT C.dict_id) district_count,
        COUNT(DISTINCT C.city_id) city_count
FROM City C
INNER JOIN District D
    ON C.dict_id = D.dict_id
INNER JOIN State S
    ON S.stateid = D.stateid
GROUP BY S.Statename
于 2013-01-29T16:19:49.960 に答える
0

You need to use GROUP BY. Try something like this:

SELECT S.StateId, S.StateName, COUNT(DISTINCT D.Dict_Id) as DictCount, COUNT(DISTINCT C.City_Id) as CityCount
FROM State S
  LEFT JOIN District D ON S.StateId = D.StateId
  LEFT JOIN City C ON D.Dict_Id = C.Dict_Id
GROUP BT  S.StateId, S.StateName

Good luck.

于 2013-01-29T16:19:43.353 に答える