oracle中行转列和列转行

本文介绍了如何在SQL中使用decode和case when函数进行行转列操作,以及通过union all实现的列转行技巧。实例演示了在GRADING和SC_GRADE表中的应用,适合数据库管理和数据分析初学者参考。
摘要由CSDN通过智能技术生成

一、行转列
在这里插入图片描述

1) 使用decode函数
select name,
sum(decode(course, ‘语文’, score, 0)) as 语文,
sum(decode(course, ‘数学’, score, 0)) as 数学,
sum(decode(course, ‘英语’, score, 0)) as 英语
from GRADE group by name;
2) 使用case when语句
select name,
sum(case course when ‘语文’ then score else 0 end) as 语文,
sum(case course when ‘数学’ then score else 0 end) as 数学,
sum(case course when ‘英语’ then score else 0 end) as 英语
from GRADE group by name;

运行结果:
在这里插入图片描述

二、列转行
在这里插入图片描述

select name, ‘语文’ [as] course, cn_score [as] score from SC_GRADE
union all
select name, ‘数学’ [as] course, math_score [as] score from SC_GRADE
union all
select name, ‘英语’ [as] course, en_score [as] score from SC_GRADE
order by name;
以语文作为值填充列名为course的列,以cn_score作为值填充列名为score的列
运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值