行列转置(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

结果集如下:

 

posted @ 2017-01-05 23:33  VNX  阅读(4627)  评论(0编辑  收藏  举报