我有以下自引用分层表:
SubCodes
ID int PK
ParentID int
Code varchar(25)
FKID int
e.g。
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 - 但它只是扭曲了我的大脑如何去做 - 任何线索?
答案 0 :(得分: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