sql - 在分层查询中查找 "deepest"子项

标签 sql oracle oracle11g connect-by transitive-closure-table

我需要一些帮助来查询分层数据。这是一个简单的表,其中 parent_id 引用 id 并且对于根条目可能为 null。

  create table edition (
      id           NUMBER(20),
      parent_id    NUMBER(20)
  );

对于表中的每条记录,我需要找到具有最大 id 的最深的 child 。如果记录没有 child ,则应返回其自己的 id。我自己尝试过,但使用 START WITH A.id = B.id 失败,其中 A 和 B 是子查询,看起来 Oracle 不允许这样的连接。

这里是示例数据:

     id      parent_id
   ----------------------
      1        NULL
      2           1
      3           1
      4           1
      5           4
      6           5
      7           5

和一个样本结果

     id      result
   ----------------------
      1           7
      2           2
      3           3
      4           7
      5           7
      6           6
      7           7

最佳答案

相信你也想试试

create table tq84_edition (
  id        number primary key,
  parent_id number references tq84_edition
);

insert into tq84_edition values (  1, null);
insert into tq84_edition values (  2,    1);
insert into tq84_edition values (  3,    1);
insert into tq84_edition values (  4,    1);
insert into tq84_edition values (  5,    4);
insert into tq84_edition values (  6,    5);
insert into tq84_edition values (  7,    5);


with x (root, id, parent_id, lvl) as (
               select id    root,
                      id,
                      parent_id,
                      1 lvl
                from  tq84_edition
        UNION ALL
               select x.root  root,
                      tq84_edition.id,
                      tq84_edition.parent_id,
                      x.lvl + 1 lvl
                 from x,
                      tq84_edition
                where x.id = tq84_edition.parent_id
)
select  root, max(id) keep (dense_rank last order by lvl, id)
  from x
 group by root;

关于sql - 在分层查询中查找 "deepest"子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11986533/

相关文章:

mysql - 不符合条件的sql联合

sql - Postgres : JOIN with first non-null value that matches?

mysql - 如何为以下操作创建 SQL 查询?

mysql - MySQL通过连接多列创建索引

sql - oracle sql组计数

java - Java Servlet 和数据库连接错误

sql - SQL 中图形结构的闭包表等价物

database - Oracle 外部表 - 指定动态文件名

sql - 如何使用 NOT IN 子句添加超过 1000 个值

sql - Oracle SQL 中的意外输出