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

Rufen Sie Datensätze aus einer bestimmten Spalte in Oracle ab

Oracle-Setup :

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;

Abfrage :

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;

Ausgabe :

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

Wenn Sie die Übereinstimmungen erhalten möchten, können Sie eine Sammlung verwenden:

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

Abfrage :

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;

oder (da ich mir nicht sicher bin MULTISET ist in 10g):

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;

Ausgabe

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