日期:2014-05-17  浏览次数:20921 次

请教大家一个SQL
原表如下
A列 B列 C列
a,b,c 1 2
b,da,a t 3
需要查询的结果
A列 B列 C列
a 1 2
b 1 2
c 1 2
b t 3
da t 3
a t 3
解释如下:
原表中A字段是由好几个字符串拼接起来的,现在需要把A字段拆分。
其中A字段记录比较多,而且不能确定是由几个字符串拼接的。
请问各位如何实现?

------解决方案--------------------
with temp as
(select a||',' a,b,c from test)
select * from (
select substr(a,1,instr(a,',',1,1)-1) a,b,c from temp
union all
select substr(a,instr(a,',',1,1)+1,instr(a,',',1,2)-instr(a,',',1,1)-1) a,b,c from temp
union all
select substr(a,instr(a,',',1,2)+1,instr(a,',',1,3)-instr(a,',',1,2)-1) a,b,c from temp)
where a is not null 
order by b,c


给一个烂的算法。。。自己看的都坑爹
可以用函数做第一个字段
------解决方案--------------------
多个字段的话就多union all几个。。。。
------解决方案--------------------
SQL code
with tb1(A ,B ,C) as(--原表
select 'a,b,c' ,'1'  ,2 from dual union all
select 'b,da,a' ,'t' ,3 from dual
)
, tb2 (newA) as(--将原表字段A合并(newA) 效果'a,b,c,b,da,a'
select wm_concat(A)  from tb1)
,
tb3 (newaa) as(--将tb2中newA进行拆分(newaa),并去重复('a','b','c','d','da')
select distinct newaa 
            from(select regexp_substr(newA,'[^,]+', 1,rownum) newaa 
                        from tb2 
                        connect by rownum<=lengthb(regexp_replace(newA,'[^,]+', ''))+1))                      
--tb1和tb2做连接,连接条件是在tb3.newaa在tb1.A能找到
select tb3.newaa,tb1.B,tb1.C 
from tb3,tb1               
where instr(tb1.A,tb3.newaa)>0
order by tb1.B,tb1.C

------解决方案--------------------
with tt as (
select 'a,b,c' as type, '1' as t1, '2' as t2 from dual union all
select 'b,da,a' as type, 't' as t1, '3' as t2 from dual 
)
select * from (
select regexp_substr(type,'[^,]+',1,(rownum-nvl((select length(replace(wm_concat(type),',','')) from (select rownum as id,tt.* from tt) b where b.id<a.id),0))
) as type,t1,t2 from (select rownum as id,tt.* from tt) a
connect by (rownum-nvl((select length(replace(wm_concat(type),',','')) from (select rownum as id,tt.* from tt) b where b.id<a.id),0)) 
<=length(replace(type,',',''))
) where type is not null;

------解决方案--------------------
探讨
不仅字段A由几个字符串拼接不确定,而且记录的行数也不确定,至少几万条