【问题标题】:Display Upper Most Hierarchy Parent for Child显示子级最高层次父级
【发布时间】:2020-01-21 23:09:26
【问题描述】:
我有一个包含父子关系的表,我想为每个孩子显示最上面的父级。真实表的顺序不会如此连续地排序,因此任何类型的排序都是不可取的。我还想避免为最大数量的层次结构级别进行手动连接。
表:
Parent Child
1 2
2 3
3 4
5 6
6 7
所以对于孩子 4 有父母 3,谁有父母 2,谁有父母 1。
4、3、2 在输出中都应该有 Parent 4。
期望的输出:
Parent Child
1 2
1 3
1 4
5 6
5 7
【问题讨论】:
标签:
sql
sql-server
tsql
recursion
common-table-expression
【解决方案1】:
;with SelectedToTopCTE as
( select ParentID, ChildID as Child, 1 as level
from Table
union all
select d.ParentID, s.ChildID, d.level + 1
from SelectedToTopCTE as d
join Table s
on d.Child = s.ParentID
)
select * INTO #SelectedToTop
from SelectedToTopCTE;
SELECT Child, MAX(level) as MaxLevel INTO #UpperMostSPLT
FROM #SelectedToTop
group by Child;
SELECT A.*
FROM #SelectedToTop A
INNER JOIN
#UpperMostSPLT B
ON A.Child = B.Child AND A.level = B.MaxLevel
ORDER BY ParentID;
【解决方案2】:
递归公用表表达式 (CTE) 可以快速遍历父/子层次结构。此示例从顶级父级开始,即上面没有父级的行。然后,它一次添加一个子级,同时跟踪最顶层的父级。
-- Sample data.
declare @Samples as Table ( Parent Int, Child Int );
insert into @Samples ( Parent, Child ) values
( 1, 2 ), ( 2, 3 ), ( 3, 4 ), ( 5, 6 ), ( 6, 7 );
select * from @Samples;
-- Run the tree.
with Tree as (
-- Start with the top level parents.
select Parent as TopLevelParent, Child
from @Samples as S
-- Where the row has no parent above it.
where not exists ( select 42 from @Samples as SS where S.Parent = SS.Child )
union all
-- Add the children one level at a time.
select T.TopLevelParent, S.Child
from Tree as T inner join
@Samples as S on S.Parent = T.Child )
-- Display the sorted results.
select TopLevelParent, Child
from Tree
order by TopLevelParent, Child;