with criteria(guy, criterion) as (
select 2,1 from dual
)
, data(son, dad) as (
select 2,1 from dual union all
select 7,1 from dual union all
select 9,1 from dual union all
select 3,2 from dual union all
select 4,2 from dual union all
select 8,7 from dual union all
select 10,9 from dual union all
select 12,9 from dual union all
select 5,4 from dual union all
select 6,4 from dual union all
select 11,10 from dual
)
, hier as (
select connect_by_root(dad) level_1_guy,
connect_by_root(son) level_2_guy,
level lvl,
son
from data
start with dad = 1
connect by dad = prior son
)
select h.son,
case when c.criterion = 1
then h.level_2_guy
else h.level_1_guy
end stop_value
from hier h
left join criteria c on h.level_2_guy = c.guy
where lvl > 1;
SON STOP_VALUE
---------- ----------
3 2
4 2
5 2
6 2
8 1
10 1
11 1
12 1