Oracle行转列、列转行的Sql语句总结

前端之家收集整理的这篇文章主要介绍了Oracle行转列、列转行的Sql语句总结前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

目录结构如下:
行转列
列转行
[一]、行转列

1.1、初始测试数据

表结构:TEST_TB_GRADE

sql代码
create table TEST_TB_GRADE
(
ID NUMBER(10) not null,
USER_NAME VARCHAR2(20 CHAR),
COURSE VARCHAR2(20 CHAR),
score FLOAT
)
初始数据如下图:



1.2、 如果需要实现如下的查询效果图:



这就是最常见的行转列,主要原理是利用decode函数、聚集函数(sum),结合group by分组实现的,具体的sql如下:
sql代码
select t.user_name,
sum(decode(t.course,'语文',score,null)) as CHINESE,'数学',null)) as MATH,'英语',null)) as ENGLISH
from test_tb_grade t
group by t.user_name
order by t.user_name


1.3、延伸

如果要实现对各门功课的不同分数段进行统计效果图如下:



具体的实现sql如下:
sql代码
select t2.score_GP,
sum(decode(t2.course,COUNTNUM,null)) as ENGLISH
from (
select t.course,
case when t.score <60 then '00-60'
when t.score >=60 and t.score <80 then '60-80'
when t.score >=80 then '80-100' end as score_GP,
count(t.score) as COUNTNUM
FROM test_tb_grade t
group by t.course,
case when t.score <60 then '00-60'
when t.score >=60 and t.score <80 then '60-80'
when t.score >=80 then '80-100' end
order by t.course ) t2
group by t2.score_GP
order by t2.score_GP

[二]、列转行

1.1、初始测试数据
表结构:TEST_TB_GRADE2
sql代码
create table TEST_TB_GRADE2
(
ID NUMBER(10) not null,
CN_score FLOAT,
MATH_score FLOAT,
EN_score FLOAT
)

初始数据如下图:



1.2、 如果需要实现如下的查询效果图:



这就是最常见的列转行,主要原理是利用sql里面的union,具体的sql语句如下:
sql代码
select user_name,'语文' COURSE,CN_score as score from test_tb_grade2
union select user_name,'数学' COURSE,MATH_score as score from test_tb_grade2
union select user_name,'英语' COURSE,EN_score as score from test_tb_grade2
order by user_name,COURSE

也可以利用【 insert all into ... select 】来实现,首先需要先建一个表TEST_TB_GRADE3:
sql代码
create table TEST_TB_GRADE3
(
USER_NAME VARCHAR2(20 CHAR),
score FLOAT
)
再执行下面的sql

sql代码
insert all
into test_tb_grade3(USER_NAME,COURSE,score) values(user_name,CN_score)
into test_tb_grade3(USER_NAME,MATH_score)
into test_tb_grade3(USER_NAME,EN_score)
select user_name,CN_score,MATH_score,EN_score from test_tb_grade2;
commit;

别忘记commit操作,然后再查询TEST_TB_GRADE3,发现表中的数据就是列转成行了。



转载自:http://www.2cto.com/database/201108/100792.html

原文链接:https://www.f2er.com/oracle/211182.html

猜你在找的Oracle相关文章