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

时间:2018-08-20 10:22:45

标签: sql oracle split

我有一张这样的桌子:

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

部门是另一个具有dept_id和dept_name作为列的表。我想要类似的结果,

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

有什么帮助吗?

2 个答案:

答案 0 :(得分:1)

with tmp_tbl as(
  select
    1 ID,
    'a' NAME,
    '2,3' DEPT_ID
  from dual
  union all
  select
    2 ID,
    'b' NAME,
    '' DEPT_ID
  from dual
  union all
  select
    3 ID,
    'c' NAME,
    '1,2' DEPT_ID
  from dual)
select
  tmp_out.ID,
  tmp_out.NAME,
  trim(tmp_out.DEPT_ID_splited)
from(
  select
    tmp.ID,
    tmp.NAME,
    regexp_substr(tmp.DEPT_ID,'[^,]+', 1, level) DEPT_ID_splited
  from
    tmp_tbl tmp
  connect by
    regexp_substr(tmp.DEPT_ID,'[^,]+', 1, level) is not null) tmp_out
group by
  tmp_out.ID,
  tmp_out.NAME,
  tmp_out.DEPT_ID_splited
order by
  tmp_out.ID,
  tmp_out.DEPT_ID_splited

答案 1 :(得分: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
相关问题