项目开发过程中涉及到oracle数据库的数据操作;但是需要将数据进行列的互转,通过查阅资料可知在oracle中有三种方式可以实现行列互转:
①使用decode 函数;
②使用case when 函数;
③使用pivot函数;
Oracle中行列互转_oracle行列转换最简单的方法https://blog.csdn.net/xiaochenXIHUA/article/details/120409641?ops_request_misc=&request_id=cb8c473afe7c418baef1d3294c3831ea&biz_id=&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~koosearch~default-1-120409641-null-null.268^v1^control&utm_term=%E8%A1%8C%E5%88%97&spm=1018.2226.3001.4450
我这里有一个数据表内容如下:
select
"name",
max(decode("course", '语文', "score")) 语文,
max(decode("course", '数学', "score")) 数学,
max(decode("course", '英语', "score")) 英语,
sum("score") 总分
from "grade"
group by "name";
select
"name",
max(case when "course" = '语文' then "score" end) 语文,
max(case when "course" = '数学' then "score" end) 数学,
max(case when "course" = '英语' then "score" end) 英语,
sum("score") 总分
from "grade"
group by "name";
pivot函数的语法:
pivot(聚合函数 for 列名 in(类型))
select t.* from(
(select * from 原表名称)
pivot(
max(需转的列名称)
for 需转的列名称 in(需转列对应的值1,需转列对应的值2,需转列对应的值3
)
)t
SELECT t.*,(t.语文+t.数学+t.英语)总分 from ((SELECT "name","course","score" from "grade")pivot
(
max("score")
for "course" in('语文' 语文,'数学' 数学,'英语' 英语)
))t ORDER BY "name";
需要转的内容如下图:
unpivot函数的语法:
SELECT 列名称,需定义的列1名称,需定义的列2名称 from 表名称 unpivot (需定义的列2名称 for 需定义的列1名称 in(列2值1,列2值2,列2值3));
SELECT "name" 名字,course 课程,score 分数 from "grade2" unpivot (score for course in("chinese","math","english"));
SELECT 名字,course 课程,score 分数 from (
SELECT "name" 名字,"chinese" 语文,"math" 数学,"english" 英语 from "grade2") unpivot (score for course in(语文,数学,英语))
透视和逆透视 Oracle Database 11g | Oracle 中国https://www.oracle.com/cn/technical-resources/articles/database/sql-11g-pivot.htmlSELECT (oracle.com)https://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_10002.htm#SQLRF01702DECODE (oracle.com)https://docs.oracle.com/cd/B28359_01/server.111/b28286/functions042.htm#SQLRF00631CASE Expressions (oracle.com)https://docs.oracle.com/cd/B28359_01/server.111/b28286/expressions004.htm#SQLRF20037