简体   繁体   中英

Get Parent Child records sql server 2008

I have COMPANY table like below

 CompanyID  CompanyName

 1           xyz
 2           xyz-c
 3           xyz-c1
 4           xyz-c2
 5           xyz-c-c
 6           xyz-c-c1
 7           xyz-c-c2
 8           xyz-c-c1-c
 9           xyz-c-c1-c1
10           xyz-c-c1-c2 

and i have a COMPANYMAPPING table like below

 CompanyMapID   ParentCompanyID ChildCompanyID
  1                 1               2               
  2                 1               3               
  3                 1               4               
  4                 2               5               
  5                 2               6               
  6                 2               7               
  7                 6               8               
  8                 6               9               
  9                 6               10              
 10                 11              12  

i want to get child company records of each and every company by using above 2 tables, precisely i want to get result like below

 CompanyID   CompanyName         Level
 1               xyz              0
 2               xyz-c            1
 3               xyz-c1           1
 4               xyz-c2           1
 5               xyz-c-c          2
 6               xyz-c-c1         2
 7               xyz-c-c2         2
 8               xyz-c-c1-c       3
 9               xyz-c-c1-c1      3
10               xyz-c-c1-c2      3

i went through some recursive CTE's butit's not fitting into this, i have multiple sets of parent child (multiple levels) records,so i need a query to fetch all the records in order

with cte as (
    select C.CompanyID, 0 as Level
    from COMPANY as C
    where C.CompanyID not in (select T.ChildCompanyID from COMPANYMAPPING as T)

    union all

    select C.ChildCompanyID as CompanyID, A.Level + 1 as Level
    from cte as A
        inner join COMPANYMAPPING as C on C.ParentCompanyID = A.CompanyID
)
select
    C.CompanyID, C.CompanyName, A.Level
from cte as A
    inner join COMPANY as C on C.CompanyID = A.CompanyID

sql fiddle demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM