Oracle Hierarchical Query输出格式

时间:2016-05-21 19:09:04

标签: oracle

我有一个表,列出了您可能为给定用户提供的所有安全项目访问号码。我正在使用Oracle db,

Security
---------
8055
8055.01
8056
8056.00
8056.01
8056.01.01
9005.01.02
9876.03

我正在尝试以对我们的treeview应用程序有用的格式获取输出表

Security       Parent ID    Group ID   Level No
------------------------------------------------
8055           null            1          1
8055.01        8055            1          2
8056           null            2          1
8056.00        8056            2          2 
8056.01        8056            2          2
8056.01.01     8056.01         2          3
9005.01.02     null            3          1
9876.03        null            4          1

任何人都可以帮助我获得上述输出格式吗?

1 个答案:

答案 0 :(得分:1)

Oracle安装程序

CREATE TABLE Table_name ( Security ) AS
SELECT '8055' FROM DUAL UNION ALL
SELECT '8055.01' FROM DUAL UNION ALL
SELECT '8056' FROM DUAL UNION ALL
SELECT '8056.00' FROM DUAL UNION ALL
SELECT '8056.01' FROM DUAL UNION ALL
SELECT '8056.01.01' FROM DUAL UNION ALL
SELECT '9005.01.02' FROM DUAL UNION ALL
SELECT '9876.03' FROM DUAL;

<强>查询

WITH parents ( security, parent_id ) AS (
  SELECT security,
         SUBSTR( security, 1, INSTR( security, '.', -1 ) - 1  )
  FROM   table_name
)
SELECT security,
       PRIOR security AS parent_id,
       DENSE_RANK() OVER ( ORDER BY CONNECT_BY_ROOT( security ) ) AS group_id,
       LEVEL AS level_no
FROM   parents p
START WITH NOT EXISTS ( SELECT 'X'
                        FROM   table_name t
                        WHERE  t.security = p.parent_id )
CONNECT BY PRIOR security = parent_id
ORDER BY security;

<强>输出

SECURITY   PARENT_ID    GROUP_ID   LEVEL_NO
---------- ---------- ---------- ----------
8055                           1          1 
8055.01    8055                1          2 
8056                           2          1 
8056.00    8056                2          2 
8056.01    8056                2          2 
8056.01.01 8056.01             2          3 
9005.01.02                     3          1 
9876.03                        4          1