-1

我的表包含以下列:TransactionID, MemberID, ParentID

这是推荐计划,一个人指的是 2 人,他们 2 指的是另外 2 人

我想从特定成员中找到最近的不平衡节点

如果我尝试找到最近的不平衡节点 001,那么我会找到尚未平衡/不完整节点的 MemberID“003”。

如果我尝试找到最近的不平衡节点 002,那么我会发现 memberID=004 尚未平衡/未完成节点。

任何人都可以帮助..

TransactionID   MemberID    ParentID
1               001          000
2               002          001
3               003          001
4               004          002
5               005          002
6               006          003
4

1 回答 1

1

AS pointed out by Martin Smith, a recursive CTE is needed. Here's something to get your started. It builds up a full node hierarchy and then picks up the first child node (i.e. one with the minimum depth in the hierarchy) that has fewer than 2 children. If two child nodes are tied on depth, the one with the smaller member_id is picked.

declare @starting_node varchar(100) = '001'
;with C as (
select parent_id root_parent, member_id, 1 as depth from #test where
parent_id = @starting_node
union all
select C.root_parent, #test.member_id, C.depth + 1 from #test join C on #test.parent_id = C.member_id
), C1 as (
select parent_id, count(*) number_of_immediate_children from #test 
group by parent_id
) 
select member_id from (
select C.member_id, ROW_NUMBER() over (order by depth, member_id) ranker
from C left join C1 on C.member_id = C1.parent_id
where isnull(number_of_immediate_children, 0) < 2
) Z where ranker = 1
于 2013-07-03T18:46:03.910 回答