0

我正在使用的数据按以下示例排序:

例子

我想知道的是:

我从我的查询中得到的是这个(带有实际数据的实际查询发布在这篇文章的末尾):

得到

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

select * from ( select distinct id , idnew , CONNECT_BY_ROOT idlast , CONNECT_BY_ISLEAF "IsLeaf" , CONNECT_BY_ISCYCLE iscycle , level seq_order from mytable tbl1 connect by NOCYCLE idnew = prior id start with not exists (select 1 from mytable tbl2 where tbl2.itemloadid = tbl. itemloadidnew) ) abc order by abc.idlast, seq_order desc

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

输出

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

非常感谢您的帮助!:)

4

1 回答 1

0

您必须反转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 演示

于 2019-02-22T17:04:03.803 回答