行列转置(Oracle)

行列转换的几种形式

  行列转换包含如下几种形式:行转列、列转行、多列转换成字符串、多行转换成字符串、字符串转换成多列、字符串转换成多行

 

一、Oracle行列转置

1、行转列

 (1)创建表格、插入测试数据

create table student(
       id number,
       name varchar2(20),
       course varchar2(20),
       score number
)

插入测试数据,如下:

(2)方法一:使用wm_concat()函数

select id, name, wm_concat(score) scores from student group by id, name;

结果集如下:      

(3)方法二:使用decode()函数

select id,name,sum(decode(course,'Chinese',score,null)) "Chinese",
               sum(decode(course,'Math',score,null)) "Math",
               sum(decode(course,'English',score,null)) "English"
       from student
       group by id,name

结果集如下:

(4)方法三:使用case表达式

select id,name,sum(case when course='Chinese' then score end) "Chinese",
               sum(case when course='Math' then score end) "Math",
               sum(case when course='English' then score end) "English"
from student
group by id,name

结果集如下:

2、列转行

(1)建表

使用上面的查询结果:

create table scores as
select id,name,sum(case when course='Chinese' then score end) "Chinese",
               sum(case when course='Math' then score end) "Math",
               sum(case when course='English' then score end) "English"
from student
group by id,name
order by i

得到表及记录如下:

(2)方法一:合并查询union

select id,name,'Chinese' as course from scores
union
select id,name,'Math' as course from scores
union
select id,name,'English' as course from scores

结果集如下:

 

转载于:https://www.cnblogs.com/chinas/p/6234587.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值