【SQL】用一条SQL语句进行不同条件统计,多条件聚合,case when ,if,sum(),count()

通过select子句进行条件分支,效率高于使用where子句

 city    orderid       sex
 北京   2984798665      男
 上海   7658545679...    ...            ...

通过订单号统计各城市的男女性销量

方法1:sum()函数聚合,此类可能会遇到没有去重问题

 select city
  ,sum(case when sex = '男' then '1' else '0' end) as cnt_m
  ,sum(case when sex = '女' then '1' else '0' end) as cnt_f
from table
group by city

等价于方法1:

 select city
  ,sum(if(sex = '男' ,'1','0')) as cnt_m
  ,sum(if(sex = '女' ,'1','0')) as cnt_f
from table
group by city

方法2:count()函数聚合,考虑去重,利用count()函数忽略null值的特性

 select city
  ,count(distinct case when sex = '男' then orderid else null end) as cnt_m
  ,count(distinct case when sex = '女' then orderid else null end) as cnt_f
from table
group by city

等价于方法2:

 select city
  ,count(distinct if(sex = '男' ,orderid ,null )) as cnt_m
  ,count(distinct if(sex = '女' ,orderid ,null )) as cnt_f
from table
group by city
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值