oracle 使用 decode函数 或 case when 实现行转列

----创建测试表

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;

转载于:https://www.cnblogs.com/hqbhonker/p/3341239.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值