sql server - SQL - how to get the top parent of a given value in a self referencing table -
i'm having small issue.
the table looks following
subject
- subjectid
- subjectname
- parentsubjectid
parentsubjectid
references subject table itself. , can go down many levels (no specific number of levels)
example (using countries sake of example):
1.europe 2.america 1.1 france 1.1 italy 2.1 usa 2.2 canada 1.1.1 paris 1.2.1 rome
and on..
subjectid guid parentsubjectid guid too.
sample overview: http://i.imgur.com/a2u2cft.png
it can keep going down in levels indefinitely (maybe street number level)
my question is: given subject (no matter depth). top parent of subject (europe/america
in case)
how can ? possible using basic sql query ?
please note cannot modify database @ (i'm querying data existing database)
write as:
declare @subject varchar(max) set @subject = 'rome'; -- set subject name here subjectcte ( select subjectid , subjectname , parentsubjectid subject subjectname = @subject union select c.subjectid , c.subjectname , c.parentsubjectid subjectcte p join subject c on p.parentsubjectid = c.subjectid ) ,subjectcte2 ( select subjectid , subjectname , parentsubjectid, row_number() on ( order subjectid asc) rownum subjectcte ) select subjectname requiredparentname subjectcte2 rownum =1
Comments
Post a Comment