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

相关文章

Java Oracle 结果集是Java语言中处理数据库查询结果的一种方...
Java AES和Oracle AES是现代加密技术中最常使用的两种AES加密...
Java是一种广泛应用的编程语言,具备可靠性、安全性、跨平台...
随着移动互联网的发展,抽奖活动成为了营销活动中不可或缺的...
Java和Oracle都是在计算机领域应用非常广泛的技术,他们经常...
Java 是一门非常流行的编程语言,它可以运行于各种操作系统上...