Oracel:列转行、行转列

列转行

unpivot函数:

  • unpivot是一种列转行函数,可以将指定字段的列转换为行
  • 可以通过将unpivot接在查询结果集的后面来实现对结果集的处理

unpivot函数用法:

unpivot(new_结果列 for new_维度列  in (column1 as 维值1,column2 as 维值1,……))

--源表数据
select * from student_score1

select  class,id,name,subject,score
from student_score1
unpivot(score for subject in (chinese as '语文',math as '数学',english as '英语'))

行转列

原表数据

方法1:pivot函数

  • pivot函数是一种行转列函数,可以将指定字段的值转换为列
  • 可以通过将unpivot接在查询结果集的后面来实现对结果集的处理

pivot函数用法:

pivot (聚合函数(取值列) for 维度列 in ((维值1 as 列1,维值2 as 列2,……))

select class,id,name,chinese,math,english
from student_score2
pivot(max(score) for subject in ('语文' as chinese,'数学' as math,'英语' as english))
order by class 

方法2:case……when……做条件取值判断

语法1:

case 条件

    when 值1 then 返回值1

    when 值2 then 返回值2

    when 值3 then 返回值3

    ……

else 返回值n

end

语法2:

case when 条件1 then 返回值1

    when 条件2 then 返回值2

    when 条件3 then 返回值3

    when 条件4 then 返回值4

    ……

else 返回值n

end

select class,id,name,
       sum(case when subject = '语文' then score else 0 end) chinese,
       sum(case when subject = '数学' then score else 0 end) math,
       sum(case when subject = '英语' then score else 0 end) english
  from student_score2
group by class,id,name
order by id
;

方法3:decode函数

对给定条件进行判断,如果条件值为指1,则得到返回值1,若条件值为指2,得到返回值2,以此类推,若条件值不满足所有给定值,则返回最后给定的一个缺省值

decode函数用法:

decode(条件,值1,返回值1,值2,返回值2,……,缺省值)

select class,id,name,
       sum(decode(subject,'语文',score,0)) chinese,
       sum(decode(subject,'数学',score,0)) chinese,
       sum(decode(subject,'英语',score,0)) chinese
  from student_score2
group by class,id,name
order by id
;

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值