oracle列转换为行

首先介绍行转换为列,

oracle行转换为列是比较常见,网上常见的例子如下:

grades表:

student  subject   grade

student1  语文     80

student1  数学     70

student1  英语     60

student2  语文     90

student2  数学     80

student2  英语     10

转换为

语文  数学    英语

Student1  80     70      60

Student2  90     80      100

执行语句如下:

Select student,

sum(decode(subject,'语文',grade,null)) "语文",

sum(decode(subject,'数学',grade,null)) "数学",

sum(decode(subject,'英语',grade,null)) "英语"

from grades

group by student order by student;
下面,介绍列转换为行的操作:

假设一个表test,记录如下:

  表头  id   proc1  proc2   proc3   
  记录  12   3.4      6.7   12.4   

  想变成如下格式:   
  表头 id   proc      value   
  记录  12  proc1       3.4   
  记录 12   proc2      6.7   
  记录 12   proc3      12.4  

方法一:采用union all方法(这种方法会随着字段的增多,变得很长,不推荐)

select id,'proc1',proc1
    from testjac where id=12
    union all
    select id,'proc2',proc2
    from testjac where id=12
    union all
    select id,'proc3',proc3
from testjac where id=12;

方法二:采用decode+系统视图USER_TAB_COLS(推荐):

select A.id,B.column_name,decode(B.column_name,'PROC1',A.proc1,'PROC2',A.proc2,'PROC3',A.proc3,null) value
from test A,(select column_name from user_tab_cols where column_id>1 and table_name='TEST') B



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值