Oracle
 sql >> Baza danych >  >> RDS >> Oracle

WYBIERZ rodzica rekordu

Możesz użyć skorelowanego podzapytania, aby znaleźć najnowsze disp_order dla poprzedniego poziomu:

Skrzypce SQL

Konfiguracja schematu Oracle 11g R2 :

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;

Zapytanie 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

Wyniki :

| 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 |


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Porównania Oracle NUMBER

  2. sprawdzanie poprawności dokumentu xml w źródle java Oracle

  3. LongOpsWatcher w SQL Dev

  4. TIMESTAMPDIFF w Oracle 11g?

  5. Wyjątek hibernacji Zapytanie nie zostało poprawnie zakończone