小编典典

将逗号分隔的值转换为多行

sql

我有一个这样的表:

ID NAME Dept_ID
1  a     2,3
2  b
3  c     1,2

Department是另一个具有dept_id和dept_name作为列的表。我想要这样的结果,

ID Name Dept_ID
 1   a    2
 1   a    3
 2   b
 3   c    1
 3   c    2

有什么帮助吗?


阅读 176

收藏
2021-04-14

共1个答案

小编典典

您可以按照以下方式进行操作:

--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;

编辑:

基于我需要加入哪一列?在一个表中,我有逗号分隔的ID,而在其他表中,我只有ID

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
2021-04-14