How to Display State Under City in SQL Server
In my DB i have Two tables like State and City. Here State id is referenced
I need to display the data First Metro City and next StateName under that City name in Alphabetical order.
For finding is metro city or not i taken a flag named IsMetrocity
Here is the solution:
select CityName,StateId from City where IsMertoCity=1
union all
SELECT sc.name,sc.StateId FROM state AS s2
LEFT JOIN (SELECT s.StateNmae AS name, s.stateid,0 as IsMertoCity FROM state s
UNION ALL
SELECT c.cityname AS name, c.StateId,IsMertoCity FROM city c ) AS sc
ON sc.stateid = s2.stateid
union all
SELECT sc.name,sc.StateId FROM state AS s2
LEFT JOIN (SELECT s.StateNmae AS name, s.stateid,0 as IsMertoCity FROM state s
UNION ALL
SELECT c.cityname AS name, c.StateId,IsMertoCity FROM city c ) AS sc
ON sc.stateid = s2.stateid
Here first 4 are the metroCities and Starting StateId 1 is StateName and remaining Cities,next starting stateid 2 is StateName remaining are Cities under the State and so on.