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