行列转置(Oracle)
2017-01-05 23:33
621 查看
一、Oracle行列转置
1、行转列
(1)创建表格、插入测试数据
create table student( id number, name varchar2(20), course varchar2(20), score number )
插入测试数据,如下:
![](https://images2015.cnblogs.com/blog/540755/201701/540755-20170105225820706-1376000707.png)
(2)方法一:使用wm_concat()函数
select id, name, wm_concat(score) scores from student group by id, name;
结果集如下:
![](https://images2015.cnblogs.com/blog/540755/201701/540755-20170105230141831-600169635.png)
(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
结果集如下:
![](https://images2015.cnblogs.com/blog/540755/201701/540755-20170105230251722-1581916607.png)
(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
结果集如下:
![](https://images2015.cnblogs.com/blog/540755/201701/540755-20170105230307472-389673050.png)
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
得到表及记录如下:
![](https://images2015.cnblogs.com/blog/540755/201701/540755-20170105230753972-1695556393.png)
(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://images2015.cnblogs.com/blog/540755/201701/540755-20170105232539769-1754198055.png)
相关文章推荐
- Oracle 行列转置
- 从Oracle 表格行列转置说起第1/2页
- Oracle 行列转置
- Oracle 表格行列转置
- 从Oracle 表格行列转置说起第1/2页
- Oracle行列转置
- Oracle 行列转置
- oracle行列转置
- 从Oracle表格行列转置说起...
- Oracle之行列转置
- oracle 行列转置功能例子
- oracle sql 行列转置
- Oracle中行列转换方法...
- Oracle 行列转换
- Oracle 中 将多行列值按照顺序合并成单值输出(connect by)
- Oracle 行列转换
- oracle恢复误删除数据,行列互换等sql语句
- 关于oracle行列转换
- 行列倒置(一)(oracle)
- ORACLE(四) 行列操作