• Try recursive cte as follows. I changed your input so that grandparent 1 has two different paths with IsAutoCalculate =(1...1,0) . You may need to tweak the query if only one path is required. I've assumed "first" means the least id within a parent.

    with src as

    (

    select * from (values

    (1,0,1,0),

    --(2,1,0,1),

    (2,1,1,1),

    (3,1,0,1),

    (4,1,0,1),

    (5,2,0,2),

    (6,2,0,2),

    (7,3,0,2),

    (8,4,0,2),

    (9,0,1,0),

    (10,9,0,1),

    (11,0,1,0),

    (12,11,1,1),

    (13,12,0,2)) as T(ID, ParentiD, IsAutoCalculate, Level)

    ), rcte as (

    select ID gId, ID, ParentiD, IsAutoCalculate, Level, cast(0 as bigint) as rn

    from src

    where ParentiD = 0

    union all

    select gId, src.ID, src.ParentiD, src.IsAutoCalculate, src.Level

    , row_number() over (order by src.IsAutoCalculate, src.ID) as rn

    from rcte

    join src on rcte.Id = src.Parentid and rcte.IsAutoCalculate = 1

    )

    select * from rcte

    where IsAutoCalculate = 0 and rn = 1

    order by gId