Reputation: 2470
I have a table like this:
I want to output the hierarchy like this:
a - c - x1
a - c - x2
a - d - y1
a - d - y2
b - e - z
b - f - q
I searched a little for CTE examples, but they list only a (2,2)-combination of the hierarchy. How can I achieve this result without depending on the parent-child depth?
Upvotes: 3
Views: 3479
Reputation: 1269563
You want to use a recursive CTE.
The following gets all paths:
with cte as (
select cast(child as varchar(max)) as path, child, 1 as lev
from t
where parent is null
union all
select cast(cte.path + ' - ' + t.child as varchar(max)), t.child, lev + 1
from cte join
t
on cte.child = t.parent
)
select *
from cte;
If you just want the paths to terminal leafs:
select *
from cte
where not exists (select 1
from t
where t.parent = cte.child
);
Upvotes: 6