我想在oracle中编写一个查询,以便我可以将我的树层次结构放在一行中,并且只显示最后一个节点路径,就像我有一个id及其父ID一样。
id parent_id
1 null
2 1
3 2
4 3
5 4
6 5
并且输出应该在一行中 路径
1-2-3-4-5-6
答案 0 :(得分:0)
使用函数sys_connect_by_path()
和伪列connect_by_is_leaf
:
select id, ltrim(sys_connect_by_path(id, '-'), '-') path
from test where connect_by_isleaf = 1
connect by prior id = parent_id
start with parent_id is null
输出和SQLFiddle:
ID PATH
--- ---------------
6 1-2-3-4-5-6
编辑: where
条款在这里很自然,但出于某种原因,您绝对不想要它。你可以使用:
select id, path from (
select id, ltrim(sys_connect_by_path(id, '-'), '-') path, connect_by_isleaf leaf
from test connect by prior id = parent_id
start with parent_id is null)
connect by 1=0 start with leaf = 1
答案 1 :(得分:0)
select LISTAGG(id, '-') WITHIN GROUP (ORDER BY id) from trea_sort connect by PRIOR id = parent start with parent is null