declare @table as table
(
Id int,
ParentId int
)
insert into @table
values (1 , null),(2,1),(3,1),(4,2),(5,2),(6,3),(7,3)
;with cte
as (select Id,ParentId,1 as [level]
from @table as t
where ParentId is null
UNION ALL
select t.Id,t.ParentId , cte.level + 1
from @table as t
join cte
on t.ParentId = cte.Id)
select *
from cte
Id | ParentId | Level |
---|---|---|
1 | NULL | 1 |
2 | 1 | 2 |
3 | 1 | 2 |
6 | 3 | 3 |
7 | 3 | 3 |
4 | 2 | 3 |
5 | 2 | 3 |
I want to get Top to Bottom Parent -> it's all descendants
and again Top to Bottom Parent -> it's descendants
but I am unable to get expected output using above query
expected output vertically in table
Id 1 -> 2 -> 4 -> 5
Id 1 -> 3 -> 6 -> 7
expected output
Id | ParentId | Level |
---|---|---|
1 | NULL | 1 |
2 | 1 | 2 |
4 | 2 | 3 |
5 | 2 | 3 |
1 | NULL | 1 |
3 | 1 | 2 |
6 | 3 | 3 |
7 | 3 | 3 |
A tree Starts from 1 and goes to bottom to find it's all child
1 -> 2 -> 4 -> 5
again tree Starts from 1 and goes to bottom to find it's all child
1 -> 3 -> 6 -> 7
1条答案
按热度按时间jdgnovmf1#
**thank you guys for your help i figured it out by myself.**it would be nice if any of you guys improve my answer, it is not best solution but currently it is what it is