oracle 多列转成一列(列转行)、 行转列

本文介绍了如何在Oracle数据库中进行列转行和行转列的操作。对于列转行,通过使用UNION结合CTE(公共表表达式)实现,将6列数据转换为两列。对于行转列,利用DECODE函数和SUM聚合函数,根据用户名称分组,展示不同科目的成绩。
摘要由CSDN通过智能技术生成

1.多列转成一列(列转行)

 

--6列转成两列(列转行)

这就是最常见的列转行,主要原理是利用SQL里面的union

with temp as
 (select
   a.iid_sn,
   a.product_name,
   a.sales_figures,
   a.selling_cost,
   a.pretax_profit,
   a.closing_inventory
    from is_import_detail a, is_import b
   where a.isi_sn = b.isi_sn
   and b.import_year=?
   and b.import_month=?
   and a.product_name=?)

--sql中要想实现特定的排序,可以适当加一些整数
select 1,'销售额' as salename, sales_figures as sale
  from temp
union
select 2,'销售成本' as salename, selling_cost as sale
  from temp
union
select 3,'税前利润' as salename, pretax_profit as sale
  from temp
union
select 5, '期末库存量' as serialname, closing_inventory as serial
  from temp

 

 

2.行转列

 

主要原理是利用decode函数、聚集函数(sum),结合group by分组实现的,具体的sql如下:

select t.user_name,
       sum(decode(t.course, '语文', score, null)) as chinese,
       sum(decode(t.course, '数学', score, null)) as math,
       sum(decode(t.course, '英语', score, null)) as english
  from test_tb_grade t
 group by t.user_name
 order by t.user_name

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值