例:
CREATE TABLE        wp_01
(
        son_id                NUMBER,
        parent_id                NUMBER
);INSERT INTO wp_01 VALUES(1, 0);
INSERT INTO wp_01 VALUES(2, 1);
INSERT INTO wp_01 VALUES(3, 2);
INSERT INTO wp_01 VALUES(4, 1);
INSERT INTO wp_01 VALUES(5, 4);
INSERT INTO wp_01 VALUES(9, 8);SQL> select * from wp_01;
    SON_ID  PARENT_ID
----------      ----------
         1          0
         2          1
         3          2
         4          1
         5          4
         9          8在这个树形结构的记录集合里我需要得到各个路径上的数据,并把每个路径区分开。
即得到两个路径:1->2->3和1->4->5
最终的数据结果的形式为:
     SON_ID          rn
----------      ----------
         1          1
         2          1
         3          1
         1          2         
         4          2
         5          2各位帮帮忙,看这个结果怎么实现。

解决方案 »

  1.   

    select a.*,level from wp_01 a
    start with parent_id=0
    connect by prior son_id=parent_id
      

  2.   


    15:00:40 scott@TUNGKONG> select * from wp_01;    SON_ID  PARENT_ID
    ---------- ----------
             1          0
             2          1
             3          2
             4          1
             5          4
             9          8已选择6行。已用时间:  00: 00: 00.01
    15:00:46 scott@TUNGKONG> with tb as
    15:00:55   2  (select level lvl,son_id,parent_id,connect_by_root son_id gp from wp_01 connect by prior son_id=parent_id
    15:00:55   3  start with parent_id in (select son_id from wp_01 where parent_id = 0))
    15:00:55   4  select son_id,rn from
    15:00:55   5  (select son_id,'1' ord,dense_rank() over(order by gp) rn,lvl from tb union all
    15:00:55   6  select parent_id,'0' ord,dense_rank() over(order by gp) rn,lvl from tb where lvl = 1)
    15:00:55   7  order by rn,ord,lvl;    SON_ID         RN
    ---------- ----------
             1          1
             2          1
             3          1
             1          2
             4          2
             5          2已选择6行。已用时间:  00: 00: 00.09