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  

check demo here..


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -