Oracle 实现行转列的几种方法

本文详细介绍了在Oracle数据库中将数据从行转换为列的三种方法:1) 使用DECODE与聚合函数,2) 使用CASE WHEN与聚合函数,3) 使用PIVOT函数。通过具体示例和查询结果展示,阐述了每种方法的实现过程和适用场景,帮助读者理解并掌握Oracle中的行转列技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

表数据

with students as
         (
             select 99 score, 'chinese' course, 'zhangsan' name
             from dual
             union all
             select 89 score, 'math' course, 'zhangsan' name
             from dual
             union all
             select 97 score, 'english' course, 'zhangsan' name
             from dual
             union all
             select 96 score, 'chinese' course, 'wangwu' name
             from dual
             union all
             select 95 score, 'math' course, 'wangwu' name
             from dual
             union all
             select 94 score, 'english' course, 'wangwu' name
             from dual
         )
select * from students

在这里插入图片描述

1 使用 decode 与聚合函数实现

select t.name,
       sum(decode(t.course, 'chinese', score, null)) as CHINESE,
       sum(decode(t.course, 'math', score, null))    as MATH,
       sum(decode(t.course, 'english', score, null)) as ENGLISH
from students t
group by t.name
order by t.name

查询结果
在这里插入图片描述

2 使用 case when 与聚合函数实现

select t.name,
       max(case when t.course = 'chinese' then t.score end) chinese,
       max(case when t.course = 'math' then t.score end)    math,
       max(case when t.course = 'english' then t.score end) english
from students t
group by t.name
order by t.name

查询结果
在这里插入图片描述

3 使用 pivot 函数

select *
from
(select course, score, name from students)
    pivot (max(score)  -- max 里是要转的列的值
    for course -- 需要转的列
    in ( 'chinese' chhinese,'math' math,'english' english ))
order by name

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值