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

Sådan vælger du værdier i en kolonne

Baseret på løsningen med regexp split du kan køre følgende forespørgsel.

Bemærk dog, at du skal kende det maksimale antal af de resulterende kolonner på forhånd.

 with t1 as (select 1 rn, 'Orcl, orcl, linux box, Pass, tablespace_name1, tablespace_name2' col from dual union all
              select 2 rn, 'Orcl2, orcl2, linux box2, Pass2, tablespace_name12, tablespace_name22' col from dual),
      t2 as (select  rownum colnum from dual connect by level <= 6 /* (max) number of columns */)
 select t1.rn, t2.colnum, rtrim(ltrim(regexp_substr(t1.col,'[^,]+', 1, t2.colnum)))  col  from t1, t2 
 where regexp_substr(t1.col, '[^,]+', 1, t2.colnum) is not null
 order by rn,colnum;
 

Dette giver dig række-, kolonne- og nøglevisning:

RN COLNUM COL ----- ---------- ------------------ 1 1 Orcl 1 2 orcl 1 3 linux box 1 4 Pass 1 5 tablespace_name1 1 6 tablespace_name2 2 1 Orcl2 2 2 orcl2 2 3 linux box2 2 4 Pass2 2 5 tablespace_name12 2 6 tablespace_name22

Du kan bruge PIVOT-forespørgslen til at få resultatet i flad tabel

 with t1 as (select 1 rn, 'Orcl, orcl, linux box, Pass, tablespace_name1, tablespace_name2' col from dual union all
              select 2 rn, 'Orcl2, orcl2, linux box2, Pass2, tablespace_name12, tablespace_name22' col from dual),
      t2 as (select  rownum colnum from dual connect by level <= 6 /* (max) number of columns */),
      t3 as (select t1.rn, t2.colnum, rtrim(ltrim(regexp_substr(t1.col,'[^,]+', 1, t2.colnum)))  col  from t1, t2 
      where regexp_substr(t1.col, '[^,]+', 1, t2.colnum) is not null)
 select * from t3
 PIVOT (max(col) col  for (colnum) in 
 (1 as "1",
  2 as "2",
  3 as "3",
  4 as "4",
  5 as "5",
  6 as "6"))
 order by rn;


    RN 1_COL     2_COL     3_COL     4_COL     5_COL              6_COL   
 ----- --------- --------- --------- --------- ---------          ---------
     1 Orcl      orcl      linux box Pass      tablespace_name1   tablespace_name2 
     2 Orcl2     orcl2     linux box2Pass2     tablespace_name12  tablespace_name22  
 

Igen, som du ser, skal du liste alle de resulterende kolonner i forespørgslen.




  1. Hvordan opretter man en MySQL hierarkisk rekursiv forespørgsel?

  2. Hvilken joinsyntaks er bedre?

  3. Forskellen mellem disse to sammenføjningstabeller?

  4. Oracle Regexp fejler i SQL