首页 > 数据库技术 > 详细

行列转置问题(Oracle)

时间:2017-01-06 01:02:50      阅读:238      评论:0      收藏:0      [点我收藏+]

一、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

结果集如下:

技术分享

 

行列转置问题(Oracle)

原文:http://www.cnblogs.com/chinas/p/6234587.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!