【问题标题】:Deriving Outline Numbering based on CONNECT BY hierarchy基于 CONNECT BY 层次结构派生大纲编号
【发布时间】:2021-11-10 01:36:49
【问题描述】:

我希望根据 CONNECT BY 查询结果创建一个自动编号的大纲。

如果我的查询结果如下:

level col1
----- --------
1     text1
1     text2
2     text3
3     text4
3     text5
1     text6

我有兴趣像这样导出数字层次结构值:

level outline col1
----- ------- --------
1     1       text1
1     2       text2
2     2.1     text3
3     2.1.1   text4
3     2.1.2   text5
1     3       text6

感觉像是sys_connect_by_path 或窗口化的lag - 但我没看到...

【问题讨论】:

  • 您的输入是什么样的? (这也将节省我们创建测试数据的时间。)

标签: sql oracle hierarchy


【解决方案1】:

您没有提供测试数据,所以我将在scott.emp 表上进行说明。

select  level,
        substr(sys_connect_by_path(rn, '.'), 2) as outline,
        empno
from    (
          select empno, mgr,
                 row_number() over (partition by mgr order by empno) as rn
          from   scott.emp
        )
start   with mgr is null
connect by mgr = prior empno
order   siblings by empno
;

LEVEL OUTLINE        EMPNO
----- -------------- -----
    1 1               7839
    2 1.1             7566
    3 1.1.1           7788
    4 1.1.1.1         7876
    3 1.1.2           7902
    4 1.1.2.1         7369
    2 1.2             7698
    3 1.2.1           7499
    3 1.2.2           7521
    3 1.2.3           7654
    3 1.2.4           7844
    3 1.2.5           7900
    2 1.3             7782
    3 1.3.1           7934

在子查询中,我们为“兄弟姐妹”(具有相同直接父级的行/员工)提供一个序列号,我们在sys_connect_by_path 中使用它。要从分层查询中获得“正确”的排序,您需要以与在子查询中对它们进行排序相同的方式对兄弟姐妹进行排序(在我的情况下,通过 empno,这是主键;在您的情况下,如果 col1 可能有重复,在两个地方按col1, rowid 订购以打破平局)。

【讨论】:

  • 这成功了。感谢您清除我的障碍:)
猜你喜欢
  • 1970-01-01
  • 2017-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-27
  • 1970-01-01
相关资源
最近更新 更多