oracle合并字段、列转行、行转列操作

一、合并字段

原理:利用wm_concat函数、group by 分组函数完成

1、建立测试表

create table test_concat
(
ID     VARCHAR2(10),
NAME   VARCHAR2(20),
TYPE  VARCHAR2(10)
)

 

2、初始化测试数据

ID  NAME  TYPE

1   jia         70

2   jia         75

3   jia         80

4   yi          75

5   yi          79

6   yi          88

 

3、执行sql

select name,wm_concat(type) type_all from test_concat group by name;

 

4、执行结果

NAME  TYPE_ALL

jia         70,75,80

jia         70,75,80

jia         70,75,80

yi          75,79,88

yi          75,79,88

yi          75,79,88

 

5、这样执行完会出现重复数据,需要做去重操作。

 

二、行转列


原理:利用sum聚焦函数、decode判断函数、group by 分组函数来综合完成。
备注:sum函数聚焦的不仅可以是number的数值类型,还可以是非数值的varchar2类型等。
1、建立测试数据表:test

create table test
(
ID     VARCHAR2(10),
NAME   VARCHAR2(20),
COURSE VARCHAR2(20),
SCORE  NUMBER
)

 

2、初始化测试数据:

ID  NAME  COURSE  SCORE

1   jia         Chinese    70

2   jia         Math         75

3   jia         English      80

4   yi          Chinese    75

5   yi          Math         79

6   yi          English      88

 

3、执行sql

 

select name,
sum(decode(course,'Chinese',score,null)) Chinese,
sum(decode(course,'Math',score,null)) Math,
sum(decode(course,'English',score,null)) English
from test
group by name
order by name;

 或者将判断函数decode换成case when执行sql

 

 

select name,
sum(case course when 'Chinese' then score else null end) Chinese,
sum(case course when 'Math' then score else null end) Math,
sum(case course when 'English' then score else null end) English
from test
group by name
order by name;

 

4、执行结果:

 

NAME  CHINESE  MATH  ENGLISH

jia         70             75        80

yi          75             79        88

 

三、行转列

 

原理:利用union函数

1、建立测试表

 

create table TEST_NEW
(
ID       VARCHAR2(10),
NAME     VARCHAR2(20),
CHINESE  VARCHAR2(10),
ENGLISH  VARCHAR2(10),
MATH     VARCHAR2(10)
)

 

2、初始化测试数据

 

ID  NAME  CHINESE  ENGLISH  MATH

1   jia         70                75             80

2   yi          76                73             88

 

3、执行sql

 

select NAME, 'CHINESE' COURSE , CHINESE as SCORE from test_new
union
select NAME, 'MATH' COURSE, MATH as SCORE from test_new
union
select NAME, 'ENGLISH' COURSE, ENGLISH as SCORE from test_new
order by NAME,COURSE

 

4、执行结果

 

NAME  COURSE  SCORE

jia         Chinese    70

jia         Math         75

jia         English      80

yi          Chinese    76

yi          Math         73

yi          English      88

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值