Oracle分拆合并表view plain /**************************************************************************************** Oracle分拆合并表 整理人:中國風(Roy)) I6 i) |8 a; I6 l$ I1 _
日期:2011.11.02 *****************************************************************************************/ % X& x8 h& m- _ /**——合并, C: J3 S! P" d! H1 I
——模拟数据Col1 Col2 1 a 1 b 1 c 2 d 2 e 3 f **/ 0 t: ]' z9 |+ n" ? /**——生成结果6 i% Y% ^ j' G3 R* a
COL1 COL2 1 a,b,c 2 d,e 3 f **/ # |7 @6 w S; q /**oracle10g以上版本字符串函数wmsys.wm_concat**/5 u9 C3 M8 C& q
/**方法1**/ with Tab as(select 1 as Col1,'a' as Col2 from dual union all select 1,'b' from dual union all select 1,'c' from dual union all select 2,'d' from dual union all select 2,'e' from dual union all select 3,'f' from dual) 8 [; { n* o2 L1 z- L" a1 Z( ] select Col1,wmsys.wm_concat(Col2 ) as Col2 from tab group by Col10 P$ v' P/ G9 y- }: O- N
/**oracle9i可以用connect by**/! A+ G8 B) b0 j1 T. f
/**方法2**/ with Tab as(select 1 as Col1,'a' as Col2 from dual union all select 1,'b' from dual union all select 1,'c' from dual union all select 2,'d' from dual union all select 2,'e' from dual union all select 3,'f' from dual); @: d% |. s: M* k3 M4 I
select Col1,substr(max(sys_connect_by_path(Col2,',')),2) Col2 from(select a.*,row_number()over(partition by Col1 order by Col1) rn from Tab a )% I' g7 x' m$ g6 N$ r
group by Col1 start with rn=1 connect by rn-1=prior rn and Col1=prior Col1 order by Col1;5 U4 p' F" O; t$ L9 P
/**——分拆. m8 d8 s2 w3 P& }
——模拟数据Col1 Col2 1 a,b,c 2 d,e 3 f **/0 x" l+ s+ w& M
/**——生成结果 6 f+ h8 ]+ e* W# L7 ?" V+ ~ COL1 COL2 1 a 1 b 1 c 2 d 2 e 3 f **/ /**方法1**/ with Tab as(select 1 as Col1,N'a,b,c' as Col2 from dual union all select 2,N'd,e' from dual union all select 3,N'f' from dual )) V" o. Z) e- \8 V* i6 R7 i
- y$ N9 n7 g6 T; h) ` v" D SELECT Col1,substr(Col2,lev,instr(Col2||',',',',lev)-lev) as Col2 from Tab,(SELECT LEVEL lev FROM DUAL CONNECT BY LEVEL