Oracle
 sql >> Database >  >> RDS >> Oracle

Oracle 11g CREATE VIEW utilizzando CONNECT BY e più tabelle

Potresti fare qualcosa del genere:

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      

Non ho alcuna clausola START WITH perché voglio avviare la query gerarchica per tutti i dipendenti. Per ogni dipendente sfoglio i dati gerarchici fino a trovare un manager che sia un membro del consiglio di amministrazione del comitato direttivo (clausola CONNECT BY).

Le query esterne filtrano le righe pertinenti.