分层查询使用 start with 子句连接

Hierarchical Query connect by using start with clause

我正在处理的数据的排序如下例所示:

Example

我想知道的是:

Want

我从查询中得到的是这样的(具有实际数据的实际查询是 posted 在此 post 的末尾):

Get

这是我现在拥有的代码,我觉得它接近于给我想要的东西。

select * 来自 ( select 不同的 ID , 新 , CONNECT_BY_ROOT idlast , CONNECT_BY_ISLEAF "IsLeaf" , CONNECT_BY_ISCYCLE 是循环 , 等级 seq_order 来自我的表 tbl1 通过 NOCYCLE 连接 idnew = prior id 从不存在开始(select 1 来自 mytable tbl2 其中 tbl2.itemloadid = tbl.itemloadidnew) ) 美国广播公司 按 abc.idlast、seq_order desc

排序

我从这段代码得到的输出是这样的:

Output

如何确保我的序列的第一个值被解释为根(而不是像现在这样的叶)?据我了解,如果将它们解释为根,我可以打印一个带有 id_first 的列,而不是我今天拥有的 id_last。

非常感谢您的帮助! :)

您必须反转 connect by 子句:

select t.*, connect_by_root(id) id_first
  from mytable t 
  start with not exists (select 1 from mytable x where x.id_new = t.id)
  connect by id = prior id_new

dbfiddle demo