Oracle中的向后层次结构

时间:2016-09-19 15:21:21

标签: sql oracle11g

我有一张桌子(好吧,它是一个CTE)我需要拉出层次结构,除了而不是parent_id,我有孩子身份......

例如

Rule_ID | Group_Name | Function_ID | Info    | Child_ID
1         'ABC'        1             '1blah'   0
1         'ABC'        2             '2blah'   3
2         'ABC'        5             '5blah'   0
2         'ABC'        6             '6blah'   7
null      'ABC'        7             '7blah'   11
null      'ABC'        11            '11blah'  0

现在另一个问题是function_id作为组的一部分是唯一的,并且Rule_id不会出现在子节点上,这是第n级。即,当Function_ID = 3存在时,它不具有相同的Rule_ID。

我需要的是:

Rule_ID | Group_Name | Function_ID | Info  
1         'ABC'        1             '1blah'
1         'ABC'        2             '2blah'
1         'ABC'        3             '3blah'
2         'ABC'        5             '5blah'
2         'ABC'        6             '6blah'
2         'ABC'        7             '7blah'
2         'ABC'        11            '11blah'

我已尝试过标准的层次结构函数,但它们似乎都基于Parent_ID,而不是Child_ID。

有人能帮我直接吗?

1 个答案:

答案 0 :(得分:1)

我认为这会做你需要的,虽然我很确定这种做法不那么笨重......

WITH sample_data AS (SELECT 1 rule_id, 'ABC' group_name, 1 function_id, '1blah' info, 0 child_id FROM dual UNION ALL
                     SELECT 1 rule_id, 'ABC' group_name, 2 function_id, '2blah' info, 3 child_id FROM dual UNION ALL
                     SELECT 2 rule_id, 'ABC' group_name, 5 function_id, '5blah' info, 0 child_id FROM dual UNION ALL
                     SELECT 2 rule_id, 'ABC' group_name, 6 function_id, '6blah' info, 7 child_id FROM dual UNION ALL
                     SELECT NULL rule_id, 'ABC' group_name, 3 function_id, '3blah' info, 0 child_id FROM dual UNION ALL
                     SELECT NULL rule_id, 'ABC' group_name, 7 function_id, '7blah' info, 11 child_id FROM dual UNION ALL
                     SELECT NULL rule_id, 'ABC' group_name, 11 function_id, '11blah' info, 0 child_id FROM dual)
SELECT sd1.rule_id,
       sd1.group_name,
       sd1.function_id,
       (SELECT info FROM sample_data sd2 WHERE sd2.function_id = sd1.function_id) info
FROM   (SELECT rule_id,
               group_name,
               connect_by_root(function_id) function_id,
               connect_by_isleaf isleaf 
        FROM   sample_data sd
        CONNECT BY PRIOR function_id = child_id
                   AND PRIOR group_name = group_name) sd1
WHERE  isleaf = 1
ORDER BY rule_id, function_id;

   RULE_ID GROUP_NAME FUNCTION_ID INFO
---------- ---------- ----------- ------
         1 ABC                  1 1blah
         1 ABC                  2 2blah
         1 ABC                  3 3blah
         2 ABC                  5 5blah
         2 ABC                  6 6blah
         2 ABC                  7 7blah
         2 ABC                 11 11blah

请记住:仅因为列标记为“child_id”并不意味着它不能成为父ID ...您只需重新标记脑中的内容