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

Recupera i record da una colonna specifica in Oracle

Impostazione Oracle :

CREATE TABLE table_name ( S_NO, id, Pid ) AS
SELECT 1, 123, 'PAQ123' FROM DUAL UNION ALL
SELECT 2, 433, 'WSD3FF' FROM DUAL UNION ALL  
SELECT 3, 565, 'PAS45E' FROM DUAL UNION ALL
SELECT 4, 123, 'PAQ123X' FROM DUAL UNION ALL
SELECT 5, 433, 'WSD3FFY' FROM DUAL UNION ALL
SELECT 6, 123, 'PAQ123Z' FROM DUAL;

Richiesta :

SELECT *
FROM   (
  SELECT t.*,
         ( SELECT COUNT(*)
           FROM   table_name x
           WHERE  t.id = x.id
           AND    LENGTH( t.Pid ) < LENGTH( x.pid )
           AND    INSTR( x.Pid, t.Pid ) = 1 ) AS num_matches
  FROM   Table_name t
)
WHERE num_matches > 0;

Risultato :

      S_NO         ID PID     NUM_MATCHES
---------- ---------- ------- -----------
         1        123 PAQ123            2 
         2        433 WSD3FF            1 

Se vuoi ottenere le corrispondenze, puoi utilizzare una raccolta:

CREATE TYPE stringlist AS TABLE OF VARCHAR2(100);
/

Richiesta :

SELECT *
FROM   (
  SELECT t.*,
         CAST(
           MULTISET(
             SELECT PID
             FROM   table_name x
             WHERE  t.id = x.id
             AND    LENGTH( t.Pid ) < LENGTH( x.pid )
             AND    INSTR( x.Pid, t.Pid ) = 1
           )
           AS stringlist
         ) AS matches
  FROM   Table_name t
)
WHERE matches IS NOT EMPTY;

o (poiché non sono sicuro di MULTISET è in 10 g):

SELECT *
FROM   (
  SELECT t.*,
         CAST(
           ( 
             SELECT COLLECT( PID )
             FROM   table_name x
             WHERE  t.id = x.id
             AND    LENGTH( t.Pid ) < LENGTH( x.pid )
             AND    INSTR( x.Pid, t.Pid ) = 1
           )
           AS stringlist
         ) AS matches
  FROM   Table_name t
)
WHERE matches IS NOT EMPTY;

Risultato

      S_NO         ID PID     MATCHES 
---------- ---------- ------- ------------------------------------
         1        123 PAQ123  TEST.STRINGLIST('PAQ123X','PAQ123Z')
         2        433 WSD3FF  TEST.STRINGLIST('WSD3FFY')