3

我有以下自引用分层表:

SubCodes

ID int PK
ParentID int
Code varchar(25)
FKID int 

例如

ID    FKID      ParentID    Code
1     25        NULL        1100
2     NULL      1           1110
3     NULL      2           1111

我想写一个查询以便我回来

FKID    Answer                IDOfLowestNode
25      '1100,1110,1111'      3

我怀疑我需要一个 CTE 和一个 PIVOT - 但这只是在扭曲我的大脑如何去做 - 任何线索?

4

1 回答 1

2

试试这个

declare @SubCodes table (ID int,ParentID int,Code varchar(25),FKID int)

insert into @SubCodes (ID,FKID,ParentID,Code)
values
(1,     25,        NULL,        1100),
(2,     NULL,      1,           1110),
(3,     NULL,      2,           1111)

;with cte as
(
  select ID RootID,ID,ParentID,Code, CAST(Code as varchar(500)) answer
  from @SubCodes
  where ParentID is null
  union all
  select cte.RootID,sc.ID,sc.ParentID,sc.Code, CAST(cte.answer+','+sc.Code as varchar(500))
  from @SubCodes sc
        join cte on cte.ID=sc.ParentID
)
select c.answer, r.id LowestNode
from cte c
     join (select RootID, MAX(id) id FROM cte GROUP BY RootID) r ON c.ID=r.id
于 2013-02-26T11:17:15.380 回答