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

Konvertieren von kommagetrennten Werten in mehrere Zeilen

Sie können dies tun als:

--Dataset Preparation 
with tab(ID, NAME,Dept_ID) as (Select 1, 'a', '2,3' from dual
                               UNION ALL
                               Select  2,  'b','' from dual
                               UNION ALL
                               Select 3,  'c' ,  '1,2' from dual)      
--Actual Query                      
select distinct ID, NAME, regexp_substr(DEPT_ID,'[^,]+', 1, level) 
from tab    
connect by  regexp_substr(DEPT_ID,'[^,]+', 1, level) is not null
order by 1;

Bearbeiten:

with tab(ID, NAME,Dept_ID) as (Select 1, 'a', '2,3' from dual
                               UNION ALL
                               Select  2,  'b','' from dual
                               UNION ALL
                               Select 3,  'c' ,  '1,2' from dual) ,
      --Table Dept
      tbl_dept (dep_id,depname) as ( Select 1,'depa' from dual
                                       UNION ALL
                                      Select 2,'depb' from dual 
                                      UNION ALL
                                      Select 3,'depc' from dual      
                                    ) ,      
       --Seperating col values for join. Start your query from here using with clause since you already have the two tables.                            
       tab_1 as (select distinct ID, NAME, regexp_substr(DEPT_ID,'[^,]+', 1, level) col3 
                from tab  
                connect by  regexp_substr(DEPT_ID,'[^,]+', 1, level) is not null
                order by 1)
--Joining table.                
Select t.id,t.name,t.col3,dt.depname
from tab_1 t
left outer join tbl_dept dt
on t.col3 = dt.dep_id
order by 1