获取父子记录sql server 2008

时间:2013-11-25 10:39:31

标签: sql sql-server sql-server-2008

我有如下表所示的公司表

 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 

我有一个像下面这样的COMPANYMAPPING表

 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  

我希望通过使用以上2个表来获取每个公司的子公司记录,我希望得到如下结果

 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

我经历了一些递归CTE的但是不适合这个,我有多套父子(多级)记录,所以我需要一个查询来按顺序获取所有记录

1 个答案:

答案 0 :(得分:0)

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