巧用行转列

select *  from  tt1;

ID      datatype      icount
---       ----------       ----------
1         1             22
2         2             22
3         3             22
1         2             22
1         3             22
1         4             22
1         5             22
1         6             22
2         1             22
....
.....
.......

 

create table tt1(id number ,datatype number,icount number);

insert into tt1 values(1,1,22);
insert into tt1 values(2,1,22);
insert into tt1 values(3,1,22);
insert into tt1 values(4,1,22);
insert into tt1 values(1,2,22);
insert into tt1 values(1,3,22);
insert into tt1 values(1,5,22);
insert into tt1 values(1,6,22);
insert into tt1 values(2,2,22);
insert into tt1 values(3,2,22);
insert into tt1 values(3,3,22);
insert into tt1 values(2,5,22);

 

查询各个id的数据类型的总数,需求为:
各个 id   的 数据类型为 1 或 2 的总数,  数类型为3 或4 的总数,数据类型为5 或 6 的总数

实验一:

 

select id,sum(case dtype when 1 then icount else 0 end) "定位",sum(case dtype when 2 then icount else 0 end) "调位",
sum(case dtype when 3 then icount else 0 end)  "通告"
from
(
with  sss  as   (select *  from tt1 )
select id,1 dtype,sum(icount) icount from sss  where   datatype in (1,2)  group by id
union all
select id,2 dtype,sum(icount) icount from sss  where datatype  in (3,4)  group by id
union all
select id,3 dtype,sum(icount) icount from sss  where datatype  in (5,6)  group by id
)  group  by id;

 


        ID       定位       调位       通告
---------- ---------- ---------- ----------
         1         44         44         44
         2         44          0         44
         3         44         22          0

 

实验二:

select id,sum(case when datatype in (1,2) then icount else 0 end) "定位",
sum(case when datatype in (3,4) then icount else 0 end)  "调位",
sum(case when datatype in (5,6) then icount else 0 end)  "通告"
from tt1 group by id;

 

        ID       定位       调位       通告
---------- ---------- ---------- ----------
         1         44         44         44
         2         44          0         44
         3         44         22          0

 

两条语句都可以实现相同的功能,但显然第二条语句更好一些。最初没有想到Oracle能将group by 后的icount多个结果进行相加,后来用了一下发现可以。

感叹Oracle 的Sql 功能还是很完善的。

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值