oracle 的sign函数,Oracle 使用sign函数分组小记

在外链网址已屏蔽看到一个使用sign分组的用法,个人觉得不错,记录下:

问题:

想知道满足下面条件的

sale > 2000 and age > 22,

sale > 2000 and age < 22,

sale < 2000 and age > 22,

sale < 2000 and age < 22

数量及sale总和:

普通写法:使用四个union all,具体的自己写,类似下面sql:

with tmp_t as(

select 1 as v_id,3000 as sale,22 as age from dual union all

select 2,2100,23 from dual union all

select 3,2300,21 from dual union all

select 4,1000,19 from dual union all

select 5,1000,23 from dual union all

select 6,2600,25 from dual union all

select 7,2200,18 from dual union all

select 8,1500,20 from dual union all

select 9,1600,35 from dual union all

select 10,2000,22 from dual union all

select 11,2000,21 from dual

)

select sum(case when sale<2000 and age<22 then 1 else 0 end) as 小于2000且age小于22,

sum(case when sale<2000 and age<22 then sale else 0 end) as sale总和,

sum(case when sale<2000 and age>22 then 1 else 0 end) as 小于2000且age大于22,

sum(case when sale<2000 and age>22 then sale else 0 end) as sale总和,

sum(case when sale>2000 and age<22 then 1 else 0 end) as 大于2000且age小于22,

sum(case when sale>2000 and age<22 then sale else 0 end) as sale总和,

sum(case when sale>2000 and age>22 then 1 else 0 end) as 大于2000且age大于22,

sum(case when sale>2000 and age>22 then sale else 0 end) as sale总和

from tmp_t

结果如下:

A184017481-74281.jpg_small.jpg

使用sign函数sql如下:

with tmp_t as(

select 1 as v_id,3000 as sale,22 as age from dual union all

select 2,2100,23 from dual union all

select 3,2300,21 from dual union all

select 4,1000,19 from dual union all

select 5,1000,23 from dual union all

select 6,2600,25 from dual union all

select 7,2200,18 from dual union all

select 8,1500,20 from dual union all

select 9,1600,35 from dual union all

select 10,2000,22 from dual union all

select 11,2000,21 from dual

)

select decode(sign(sale-2000),1,'大于2000',-1,'小于2000'),decode(sign(age-22),1,'大于22',-1,'小于22'),count(1),sum(sale)

from tmp_t

group by sign(sale-2000),sign(age-22)

having sign(sale-2000)*sign(age-22)<>0

order by sign(sale-2000),sign(age-22)

结果如下:

A184019840-74281.jpg_small.jpg

全文完。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值