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?
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?
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
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.