[英]Tree Hierarchy in Oracle
我刚刚从“ HackerRank”遇到了这个问题。 BST
表包含两列N
和P
N
代表Node, P
代表Parent:
N P
-- --
1 2
3 2
6 8
9 8
2 5
8 5
5 null
样本输出应为:
1 leaf
2 inner
3 leaf
5 root
6 leaf
8 inner
9 leaf
我试过的是:
select N,
case
when level = 3 then 'leaf'
when level = 2 then 'inner'
else 'root'
end
from BST
start with P is NULL
connect by P = prior N
order by N;
尽管它给出了正确的结果,但是我对代码不满意,因为它对名称进行了硬编码(无论是叶子,内部还是根)。 当树中有多个层次结构时,此代码也会失败。
有人可以建议其他优雅的方式编写同一代码,以确保它不会在多个层次结构中失败吗?
您可以使用connect_by_isleaf
伪列 ,以及根将始终具有级别1的事实:
select n,
case
when connect_by_isleaf = 1 then 'leaf'
when level = 1 then 'root'
else 'inner'
end
from bst
start with p is null
connect by p = prior n
order by n;
Oracle提供了一个伪列CONNECT_BY_ISLEAF
来测试叶性。 对root的测试与START WITH子句相同。 其他任何东西都是内在的。 所以这应该做
select N ,
case
when CONNECT_BY_ISLEAF = 1 then 'leaf'
WHEN P is NULL then 'root'
else 'inner'
end
from BST
start with P is NULL
connect by P = prior N
order by N;
请使用下面的用户(对于MS SQL层次结构)
;与层次结构(ChildId,Generation,ParentId)AS(SELECT Id,0 AS Generation,ParentId FROM Table_Name AS FirtGeneration WHERE ParentId IS NULL
UNION ALL SELECT NextGeneration.Id,Parent.Generation + 1,Parent.ChildId来自Table_Name AS NextGeneration内部联接层次结构AS父级ON NextGeneration.ParentId = Parent.ChildId
)
SELECT * FROM Hierarchy ORDER BY Generation;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.