分层查询麻烦

时间:2016-10-27 16:34:36

标签: sql oracle

我需要进行分层查询以选择“中心”及其所有父级(最多5个父级)。由于商业原因,它必须是6行,所以如果我的中心只有两个父母,我必须用我的实际中心完成表格。 我完成了第一部分:

SELECT centro as center, nodo as node , nodo_padre as father_node, 
level as Lvl
FROM BUP01.NODOTREE
where rownum < 7
START WITH NODO = 35250453 
CONNECT BY  NODO= PRIOR NODO_PADRE 
order by lvl desc

得到这个:

|CENTER    | NODE                | FATHER_NODE         |        LVL|
|----------| --------------------| --------------------| ----------|
|000-101   | 1                   | 0                   |          3|
|000-102   | 25974018            | 1                   |          2|
|000-107   | 35250453            | 25974018            |          1|

但我需要执行一个抛出下一个结果的查询:

|CENTER     |NODE                 |FATHER_NODE         |        LVL|
|---------- |-------------------- |--------------------| ----------|
|000-101    |1                    |0                   |          6|
|000-102    |25974018             |1                   |          5|
|000-107    |35250453             |25974018            |          4|
|000-107    |35250453             |25974018            |          3|
|000-107    |35250453             |25974018            |          2|
|000-107    |35250453             |25974018            |          1|

1 个答案:

答案 0 :(得分:1)

with t as
(
  SELECT          centro as center, nodo as node , nodo_padre as father_node, level as Lvl
  FROM            NODOTREE
  START WITH      NODO = 35250453 
  CONNECT BY      NODO = PRIOR NODO_PADRE
              and level <= 6
)

select          center,node,father_node,lvl+(6-count(*) over ()) as lvl

from            t

union all

select          center,node,father_node,level as lvl

from           (SELECT    centro as center, nodo as node , nodo_padre as father_node
                FROM      NODOTREE
                where     NODO = 35250453 
                      and 6 - (select count (*) from t) > 0
                )

connect by      level <= 6 - (select count (*) from t)

order by        lvl desc
;