可变级别的递归自连接 - ORACLE

时间:2013-11-06 10:37:28

标签: sql oracle hierarchical-data

我有下表:

+----+---------+----------------+
| ID | COMPANY | PARENT_COMPANY |
+----+---------+----------------+
|  1 | A       | X              |
|  2 | B       | Y              |
|  3 | C       | Z              |
|  4 | D       | A              |
|  5 | E       | D              |
+----+---------+----------------+

我需要检索某个公司和所有后代,无论它们有多少以及它们扩展了多少级别。

例如,公司A有孩子D,后者又有孩子E等等。我想在一栏中展示所有这些公司。

我厌倦了自我加入,但我认为它的数量是固定的。我在这里检查了ORACLE相关的问题,我找到了this,但是级别的数量是有限的。

1 个答案:

答案 0 :(得分:1)

使用WITH子句:

WITH rt (
    COMPANY,
    CHILD_COMPANY
) AS (
    SELECT
        t.COMPANY,
        t.COMPANY AS CHILD_COMPANY
    FROM
        Test t
    WHERE
        t.COMPANY = 'A' /* selected company */
UNION ALL
    SELECT
        rt.COMPANY,
        t.COMPANY AS CHILD_COMPANY
    FROM
        rt
    JOIN
        Test t
    ON
        rt.CHILD_COMPANY = t.PARENT_COMPANY
)
SELECT
    rt.COMPANY,
    LISTAGG(rt.CHILD_COMPANY, ', ') WITHIN GROUP (ORDER BY rt.CHILD_COMPANY) AS DESCENDANTS
FROM
    rt
WHERE
    rt.COMPANY <> rt.CHILD_COMPANY  /* exclude self-match */
GROUP BY
    rt.COMPANY;