在分层数据中,如何选择所有节点直到根级?
如果我有像这样的表格中表示的分层数据:
team_id team_name parent_id
1 Sales (null)
2 Executives (null)
3 EMEA Sales 1
4 APAC Sales 1
5 UK Sales 3
给定一个team_id,那么SQL将选择所有导致根级别的team_ids是什么? 我正在使用Oracle 11.2。
例如,给定team_id 5,返回的team_ids应该是:(5,3,1)
或者,给定team_id 4,那么输出应该是:(4,1)
遍历树分支是合理的微不足道的,显示数据层次结构,使用如下所示:
SELECT team_id, team_name, parent_id
FROM teams
START WITH team_name = 'Sales'
CONNECT BY PRIOR team_id = parent_id
;
我正在寻找相反的东西 - 遍历来自特定节点的树枝。
请注意,这里的示例数据只有3个级别,但我正在寻找任意级别的解决方案。
WITH test AS
( SELECT 1 team_id, 'Sales team_name', NULL parent_id FROM dual
UNION
SELECT 2, 'Executives' , NULL FROM dual
UNION
SELECT 3, 'EMEA Sales', 1 FROM dual
UNION
SELECT 4, 'APAC Sales', 1 FROM dual
UNION
SELECT 5, 'UK Sales' , 3 FROM dual
)
SELECT team_id
FROM test
START WITH team_id = 5
CONNECT BY prior parent_id = team_id
链接地址: http://www.djcxy.com/p/93923.html
上一篇: In hierarchical data, how to select all nodes up to the root level?
下一篇: Oracle Tree Structure Hierarchy Data Display in Single Row Different Column