为什么你的预期输出是它是什么它不是完全清楚给我。从6-10的路径不是10的完整路径:该路径始于ID 5.我已经写了输出的完整路径,说明你会如何去这样做的例子。如果你确实希望它由于某种原因从6开始,那么请清楚地说明确定哪些节点应该作为结果集中的起点出现的规则。
我注意到,在您的样本数据中的每个ID只能有一个前身,但潜在的多个接班人。出于这个原因,我选择从识别端点节点开始,然后回溯到起点。希望下面的代码注释足以解释正在发生的其他事情。
declare @TableX table (FromID int, ToID int);
insert @TableX values (1, 2), (2, 3), (3, 4), (5, 6), (6, 7), (6, 9), (9, 10);
with PathCTE as
(
-- BASE CASE
-- Any ID that appears as a "to" but not a "from" is the endpoint of a path. This
-- query captures the ID that leads directly to that endpoint, plus the path
-- represented by that one row in the table.
select
X1.FromID,
[Path] = convert(varchar(max), X1.FromID) + ',' + convert(varchar(max), X1.ToID)
from
@TableX X1
where
not exists (select 1 from @TableX X2 where X2.FromID = X1.ToID)
union all
-- RECURSIVE CASE
-- For every path previously identified, look for another record in @TableX that
-- leads to its starting point and prepend that record's from ID to the overall path.
select
X.FromID,
[Path] = convert(varchar(max), X.FromID) + ',' + PathCTE.[Path]
from
PathCTE
inner join @TableX X on PathCTE.FromID = X.ToID
)
-- Any ID that appears as a "from" but not a "to" is the starting point of one or more
-- paths, so we get all results beginning at one of those points. All other output from
-- PathCTE is partial paths, which we can ignore.
select *
from
PathCTE
where
not exists (select 1 from @TableX X where PathCTE.FromID = X.ToID)
order by
FromID, [Path];
输出:
FromID Path
1 1,2,3,4
5 5,6,7
5 5,6,9,10
所以2-3将不获得自己的行,但6-9会因为你有6-7以前? –
嗨,为了简化,我已经拿出6-9。它就像一棵树结构,其中1,5,9是根ID。我需要每个根的孩子ID – user3050151