Sql 将逗号分隔值转换为多行
我有一张这样的桌子:Sql 将逗号分隔值转换为多行,sql,oracle,split,Sql,Oracle,Split,我有一张这样的桌子: 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 有什么帮助吗?您可以通过以下方式完成: with tmp_tbl as( select 1 ID, 'a' NAME,
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
有什么帮助吗?您可以通过以下方式完成:
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
--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
如果我有1000多行,那么如何准备数据集?可能重复?@learner1您不必准备数据集。我准备它只是为了给你看。您可以直接使用标记为
Actaul query
的查询。嘿,我必须再做一次更改,而不是dept\u id,我想从tbl\u dept表中显示相应id的部门名称,这可能吗?Yrs..这是可能的。与表进行联接,并在select语句中添加所需的列。根据哪一列需要联接?在一个表中,我有逗号分隔的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