Oracle
 sql >> Base de Dados >  >> RDS >> Oracle

Oracle 11g CREATE VIEW usando CONNECT BY e várias tabelas


Você poderia fazer algo assim:
SQL> SELECT *
  2    FROM (SELECT empl_id, ename, report_to,
  3                 member_id, board_position,
  4                 MAX(lvl) over(PARTITION BY empl_id) maxlvl, lvl
  5             FROM (SELECT connect_by_root(e.empl_id) empl_id,
  6                          connect_by_root(e.ename) ename,
  7                          bm.empl_id report_to,
  8                          LEVEL lvl, bp.*
  9                      FROM emp e
 10                      LEFT JOIN board_members bm
 11                             ON e.empl_id = bm.empl_id
 12                      LEFT JOIN board_positions bp
 13                             ON bm.member_id = bp.member_id
 14                    CONNECT BY NOCYCLE e.empl_id = PRIOR e.report_to
 15                           AND (PRIOR bp.board_position IS NULL
 16                                OR PRIOR bp.board_position != 'LDRSHPCOMM')))
 17   WHERE lvl = maxlvl;

EMPL_ID ENAME                            REPORT_TO MEMBER_ID BOARD_POSITION     
------- -------------------------------- --------- --------- ------------------ 
FLUNKY  Ida Dunnit                       INFGUY    CIO       LDRSHPCOMM         
HITECH  Number 2                         INFGUY    CIO       LDRSHPCOMM         
INFGUY  Comp U Turk                      INFGUY    CIO       LDRSHPCOMM         
LOTECH  Number 3                         INFGUY    CIO       LDRSHPCOMM         
OPSGUY  Meikut Work                      OPSGUY    COO       LDRSHPCOMM         
PROGMR  Nameless Blameless               INFGUY    CIO       LDRSHPCOMM         
TOPDOG  Big Guy                          TOPDOG    CEO       LDRSHPCOMM         
WALLET  Money Bags                       WALLET    CFO       LDRSHPCOMM      

Não tenho cláusula START WITH porque quero iniciar a consulta hierárquica para todos os funcionários. Para cada funcionário, percorro os dados hierárquicos até encontrar um gerente que seja membro do conselho no comitê de liderança (cláusula CONNECT BY).

As consultas externas filtram as linhas relevantes.