Oracle
 sql >> Datenbank >  >> RDS >> Oracle

WÄHLEN Sie das übergeordnete Element eines Datensatzes aus

Sie können eine korrelierte Unterabfrage verwenden, um die neueste disp_order zu finden für die vorherige Ebene:

SQL-Geige

Oracle 11g R2-Schema-Setup :

CREATE TABLE tbl_pattern ( order_no, code, disp_order, lvl, description ) AS
SELECT 'RM001-01', 1, 0, 1, 'HK140904-1A' FROM DUAL UNION ALL
SELECT 'RM001-01', 1, 1, 2, 'HK140904-1B' FROM DUAL UNION ALL
SELECT 'RM001-01', 1, 2, 3, 'HK140904-1B' FROM DUAL UNION ALL
SELECT 'RM001-01', 1, 3, 4, 'HK140904-1C' FROM DUAL UNION ALL
SELECT 'RM001-01', 1, 4, 5, 'HK140904-1D' FROM DUAL UNION ALL
SELECT 'RM001-01', 1, 5, 2, 'HK140904-1E' FROM DUAL UNION ALL
SELECT 'RM001-01', 1, 6, 3, 'HK140904-1E' FROM DUAL UNION ALL
SELECT 'RM001-01', 1, 7, 3, 'HK140904-1X' FROM DUAL UNION ALL
SELECT 'RM001-01', 1, 8, 4, 'HK140904-1E' FROM DUAL UNION ALL
SELECT 'RM001-01', 1, 9, 5, 'HK140904-1E' FROM DUAL;

Abfrage 1 :

SELECT t.*,
       ( SELECT MAX( disp_order )
         FROM   tbl_pattern p
         WHERE  p.order_no   = t.order_no
         AND    p.code       = t.code
         AND    p.lvl        = t.lvl - 1
         AND    p.disp_order < t.disp_order ) AS parent
FROM   tbl_pattern t

Ergebnisse :

| ORDER_NO | CODE | DISP_ORDER | LVL | DESCRIPTION | PARENT |
|----------|------|------------|-----|-------------|--------|
| RM001-01 |    1 |          0 |   1 | HK140904-1A | (null) |
| RM001-01 |    1 |          1 |   2 | HK140904-1B |      0 |
| RM001-01 |    1 |          2 |   3 | HK140904-1B |      1 |
| RM001-01 |    1 |          3 |   4 | HK140904-1C |      2 |
| RM001-01 |    1 |          4 |   5 | HK140904-1D |      3 |
| RM001-01 |    1 |          5 |   2 | HK140904-1E |      0 |
| RM001-01 |    1 |          6 |   3 | HK140904-1E |      5 |
| RM001-01 |    1 |          7 |   3 | HK140904-1X |      5 |
| RM001-01 |    1 |          8 |   4 | HK140904-1E |      7 |
| RM001-01 |    1 |          9 |   5 | HK140904-1E |      8 |