Oracle 行转列与列转行

Oracel 行转列与列转行

一、 列转行
1. 使用函数:wm_concat()
2. 函数说明:该函数将某一列,根据条件转换成一行(相当于把列里的值合并,并用逗号区分各个值)
3. 例子:

表 testT 中有数据如下所示:
xh  age
1    11
1    12
1    13

2    21
2    22

3    31

Sql:
select t.xh, wm_concat(t.age) age from testT t group by t.xh;

查询结果如下所示:
xh  age
1    11,12,13
2    21, 22
3    31

PS: wm_concat() 函数还可以与 over\order by 联合使用, 这里不再复述, 感兴趣的可以去查询了解一下。

二、 行转列
1. 使用函数: regexp_substr()、regexp_replace()、level(connect by)、length()
2. 原理说明: 使用level...connect by.. 和 length() 来控制转换后列的数量
                       使用regexp_substr()控制如何拆分
3. 例子:

现有数据如下:
11,12,13

sql:
select regexp_substr('11,12,13', '[^,]+', 1, level) age from dual
connect by level <= (
                     Length('11,12,13') - Length(regexp_replace('11,12,13', ',', '')) + 1
                    );

转换后的结果如下所示:
age
11
12
13

PS: 这里使用到了正则表达式,有兴趣的可以看下这篇文章:

http://xuzonghua-itianyi-com.iteye.com/blog/2048219

猜你喜欢

转载自xuzonghua-itianyi-com.iteye.com/blog/2048235