oracle中行转列操作

Posted 道法自然

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了oracle中行转列操作相关的知识,希望对你有一定的参考价值。

数据准备阶段:

CREATE TABLE CC  (Student NVARCHAR2(2),Course NVARCHAR2(2),Score INT); 

INSERT into CC   
select N\'张三\',N\'语文\',78 from dual union all  
select N\'张三\',N\'数学\',87 from dual union all  
select N\'张三\',N\'英语\',82 from dual union all  
select N\'张三\',N\'物理\',90 from dual union all  
select N\'李四\',N\'语文\',65 from dual union all  
select N\'李四\',N\'数学\',77 from dual union all  
select N\'李四\',N\'英语\',65 from dual union all  
select N\'李四\',N\'物理\',85 from dual ;  
commit; 

操作如下:

方法一、

select 
student,
sum(decode(course,\'语文\',score)) 语文,
sum(decode(course,\'数学\',score)) 数学,
sum(decode(course,\'英语\',score)) 英语,
sum(decode(course,\'物理\',score)) 物理,
sum(score)
from cc group by student;

 

 方法二、

SELECT KIN.*,  
  KIN.a+KIN.b+KIN.c+KIN.d AS TOTAL  
FROM  
  (SELECT   *  
  FROM CC PIVOT ( MAX(SCORE) FOR COURSE IN (\'语文\' AS A , \'数学\' AS B, \'英语\' AS C,\'物理\' AS D) )  
  ) KIN; 

 

方法三、

select 
student,
sum(case when course = \'语文\' then score else 0 end )语文,
sum(case when course = \'数学\' then score else 0 end )数学,
sum(case when course = \'英语\' then score else 0 end )英语,
sum(case when course = \'物理\' then score else 0 end )物理
from cc group by student;

完。

以上是关于oracle中行转列操作的主要内容,如果未能解决你的问题,请参考以下文章

Mysql中行转列和列转行

SQL中行转列(PIVOT)与列转行(UNPIVOT)

C#中DataTable行转列示例

oracle 行求和

Oracle数据 行转列

oracle 逗号分割,列转行,行转列 转载