首頁 > 資料庫 > mysql教程 > oracle decode 函数实现行转列

oracle decode 函数实现行转列

WBOY
發布: 2016-06-07 14:55:19
原創
1387 人瀏覽過

用decode函数,或者case when实现行转列 Oracle ----创建测试表create table student_score( name varchar2(20), subject varchar2(20), score number(4,1) ); -----插入测试数据insert into student_score (name,subject,score)values('张三','语文',78); in

用decode函数,或者case when实现行转列
Oracle
----创建测试表

create table student_score(

       name varchar2(20),

       subject varchar2(20),

       score number(4,1)

 

);

 

-----插入测试数据

insert into student_score (name,subject,score)values('张三','语文',78);

 

insert into student_score (name,subject,score)values('张三','数学',88);

 

insert into student_score (name,subject,score)values('张三','英语',98);

 

 

insert into student_score (name,subject,score)values('李四','语文',89);

 

insert into student_score (name,subject,score)values('李四','数学',76);

 

insert into student_score (name,subject,score)values('李四','英语',90);

 

 

insert into student_score (name,subject,score)values('王五','语文',99);

 

insert into student_score (name,subject,score)values('王五','数学',66);

 

insert into student_score (name,subject,score)values('王五','英语',91);

 

-----decode行转列

select name "姓名",

       sum(decode(subject, '语文', nvl(score, 0), 0)) "语文",

       sum(decode(subject, '数学', nvl(score, 0), 0)) "数学",

       sum(decode(subject, '英语', nvl(score, 0), 0)) "英语"

  from student_score

 group by name;

 

------ case when 行转列

 

select name "姓名",

       sum(case when subject='语文'

       then nvl(score,0)

       else 0

       end) "语文",

       sum(case when subject='数学'

       then nvl(score,0)

       else 0

       end) "数学",

       sum(case when subject='英语'

       then nvl(score,0)

       else 0

       end) "英语"

      from student_score

       group by name;
登入後複製
相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板