sql - Getting Parent of Parent in Self Join Table -


i have self join table. table being used join 4 level, i.e.;

region -> country -> county -> town 

how can parent of parent of town. 2 level query

select t.shortname town,        (select c.shortname locations c                 c.locationid = t.parentid) county locations t t.locationid = 100 

now want country parent of county.

either hardcode join or use recursive cte.

;with locs ( select 1 level, shortname, parentid locations  locationid = 100 union select level + 1, l.shortname, l.parentid locations l  join locs on locs.parentid = l.locationid ) select * locs; 

Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -