oracle 大表sum decode,Oracle 几种行转列的方式 sum+decode sum+case when pivot

原始数据:

5643dfadf848ea933d8435cc0141bad6.png

方式一:

select t_name,

sum(decode(t_item, 'item1', t_num, 0)) item1,

sum(decode(t_item, 'item2', t_num, 0)) item2,

sum(decode(t_item, 'item3', t_num, 0)) item3,

sum(t_num) total

from test

group by t_name;

02b00ad3eb63a702de9f88bc45b9597f.png

方式二:

select t_name,

sum(case

when t_item = 'item1' then

t_num

else

0

end) item1,

sum(case

when t_item = 'item2' then

t_num

else

0

end) item2,

sum(case

when t_item = 'item3' then

t_num

else

0

end) item3,

sum(t_num) total

from test

group by t_name;

83e63ebdebe7460fe0fb8d451b28fbcf.png

方式三:

select t.*, (nvl(t.item1, 0) + nvl(t.item2, 0) + nvl(t.item3, 0)) as total

from (select *

from test pivot(sum(t_num) for t_item in('item1' as item1,

'item2' as item2,

'item3' as item3))) t;

3511431ea8ebaa7e7f1b88fac1607232.png

unpivot的使用:

select t_name, t_item, t_num

from (

select *

from test pivot(sum(t_num) for t_item in('item1' as item1,

'item2' as item2,

'item3' as item3))

) unpivot(t_num for t_item in(item1,item2,item3));

5bafd7bf9c367d3941bddf7bfd258c5f.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值