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

How to extract a hierarchical structure from a flat table?

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

+----+--------+----------------+---------------------+
| 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 分层查询的内容,但我不知道如何使用我的 table 结构来实现... 最后,我必须让 JSON 显示在网页上。 为了方便起见,我在sqlfiddle上准备了一个table

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

一种方法如下(使用 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