Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Recursive Query - Find Grandparent

Status
Not open for further replies.

Moebius01

Programmer
Oct 27, 2000
309
US
Ok, first off, hopefully this will be at least understandable - medication has my head swimming right now. Second, if this is really simple, it's the drugs making me miss it. :)

Basically, I have a table (SQL 2000, not 2005) with a parent/child structure for three levels. Something like this:

ID Name ParentID Type
1 USA null Country
2 South 1 Region
3 East 1 Region
4 Texas 2 City
5 Boston 3 City

What I need to do is resolve the Country from the city level as simply as possible. Ultimately, I need to use it in a join from another table storing employee data. i.e. Select the employees who have a city_id in USA.

I'm running around in circles (or circular references) on this at the moment, so any help would be most appreciated.
 
Select *
from table
inner join(Select *
from table
where type = 'Region')Regions
on Regions.id=table.parent
inner join(Select *
from table
where type = 'Country')Countries
on Countries.id=Regions.parent
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top