如何从平面表中提取层次结构?

时间:2019-05-16 08:34:27

标签: sql oracle hierarchy hierarchical-data

我想从oracle数据库的表中提取层次结构。 表格看起来像这样:

+----+--------+----------------+---------------------+
| id | lvl1   | lvl2           | lvl3                | 
+----+--------+----------------+---------------------+
| 1  | Oracle | Marketing unit | Internet            | 
+----+--------+----------------+---------------------+
| 2  | Oracle | Lawyers unit   | Intellectual        | 
+----+--------+----------------+---------------------+
| 3  | Oracle | Finance unit   | null                |
+----+--------+----------------+---------------------+
| 4  | Oracle | Lawyers unit   | Judicial department | 
+----+--------+----------------+---------------------+
| 5  | Oracle | IT unit        | Database            |
+----+--------+----------------+---------------------+
| 6  | Oracle | Marketing unit | Television          | 
+----+--------+----------------+---------------------+
| 7  | Oracle | IT unit        | ERP                 | 
+----+--------+----------------+---------------------+

这就是我想要得到的:

- Oracle
. - Marketing unit
.   - Internet
.   - Television 
. - Lawyers unit
.   - Intellectual
.   - Judicial department
. - Finance unit
. - IT unit
.   - Database
.   - ERP

我读到有关Oracle分层查询的信息,但是我不知道如何使用我的表结构来实现它... 最后,我必须获取JSON才能在网页上显示。 为了方便起见,我在sqlfiddle上准备了一张桌子

感谢您的帮助, 有什么想法吗?

1 个答案:

答案 0 :(得分:3)

一种方法如下(使用UNPIVOT):

WITH unpiv AS (SELECT lvl, par, cur, MIN(id) id FROM HIERARCHY_SAMPLE
               unpivot ((par, cur) for lvl in ((lvl1 /*Something here - it doesn't really matter */,lvl1) as 1
                                              ,(lvl1,lvl2) as 2
                                              ,(lvl2,lvl3) as 3))
                WHERE cur IS NOT NULL
               GROUP BY lvl,par,cur)
SELECT LPAD('- ', LEVEL*2)||cur 
  FROM unpiv
START WITH lvl = 1
CONNECT BY lvl = PRIOR lvl + 1
       AND par = PRIOR cur
ORDER siblings BY id