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

VÆLG den overordnede for en post

Du kan bruge en korreleret underforespørgsel til at finde den seneste disp_order for det forrige niveau:

SQL violin

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;
 

Forespørgsel 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
 

Resultater :

| 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. Hvad svarer til sort hul?

  2. Del forbindelse til postgres db på tværs af processer i Python

  3. Indsæt nye rækker fra lokal tabel til fjerntabel

  4. laravel søg flere ord adskilt af mellemrum