PL/SQL 实现行列转换

 这篇博文写的是简单的行列转换的,以一个具体的例子来给出。

  以前在论坛上有人问过相关的问题,上面的回答五光十色,有很多是可行的,当然更多的是自以为很高端,实际却不着边际的回答。下面进入正题。

part1:列转行。需求:

示例给出这么一张表:

表定义如下:

复制代码
create table TEST_TB_GRADE 
( 
  ID        NUMBER(10) not null, 
  USER_NAME VARCHAR2(20 CHAR), 
  COURSE    VARCHAR2(20 CHAR), 
  SCORE     FLOAT 
) 
复制代码

要求转换成为:

下面给出一个可行的PL/SQL语句:

复制代码
select t.user_name as 姓名, 
  sum(decode(t.course, '语文', score,null)) as 语文, 
  sum(decode(t.course, '数学', score,null)) as 数学, 
  sum(decode(t.course, '英语', score,null)) as 英语 
from test_tb_grade t 
group by t.user_name 
order by t.user_name
复制代码

实现效果如下图需求所示。

Part2:行转列。需求:

示例给出这样一张表

表结构如下:

复制代码
create table TEST_TB_GRADE2 
( 
  ID         NUMBER(10) not null, 
  USER_NAME  VARCHAR2(20 CHAR), 
  CN_SCORE   FLOAT, 
  MATH_SCORE FLOAT, 
  EN_SCORE   FLOAT 
) 
复制代码

需要转换成如下形式:

下面给出一个可执行的PL/SQL语句:

复制代码
select user_name, '语文' as COURSE , CN_SCORE as SCORE from test_tb_grade2  
union all
select user_name, '数学' as COURSE, MATH_SCORE as SCORE from test_tb_grade2  
union all
select user_name, '英语' as COURSE, EN_SCORE as SCORE from test_tb_grade2  
order by user_name,COURSE
复制代码

实现效果如下图需求所示。

本文旨以一个具体的例子,给出一种Oracle中行列转换的方案,没有什么可圈可点的地方,欢迎给出其他实现,也欢迎批评指正!

转自:http://www.cnblogs.com/DebugLZQ/archive/2012/07/23/2604687.html

原文地址:https://www.cnblogs.com/jieqing/p/3490060.html