Oracle使用count和case when配合统计

      在使用Oracle的项目中写查询语句,发现count搭配case when特别好用,以前没怎么用过,网上也找了些资料再次记录下来


1、我们知道,SQL语句中用count函数统计记录数量,配合distinct关键字可以统计非重复的记录数量。例如:
select count(*), count(city_name), count(distinct city_name) from tb_county 

查询结果是:

count(*)count(city_name)count(distinct city_name)
25342534363
增加查询条件可以查询不同条件下记录的数量,例如:
select count(*), count(city_name), count(distinct city_name)
  from tb_county 
 where xs_code like '23%'
    or xs_code like '24%'

查询结果是:

count(*)count(city_name)count(distinct city_name)
858516
2、如果我们需要统计总记录数量和某种条件下的数量,可以用 sum函数 函数和case when语句配合,例如:
select count(*),
   sum(case when xs_code like '23%' or xs_code like '24%'               
       then 1
       else 0
       end)
  from tb_county 

查询结果是:

count(*)sum
253485
3、如果我们需要统计总记录数量和某种条件下非重复的记录数量,用上面的sum函数就不行了。这时我们可以用count函数和case when语句配合,满足条件取字段值,否则为空(null),因为count函数是不统计空值的,所以可以统计该条件下的记录数量(和上面的sum函数功能一样),如果再配合distinct关键字,就可以统计该条件下非重复的记录数量了。例如:
select count(*),count(city_name),count(distinct city_name),
       count(case 
       when xs_code like '23%' or xs_code like '24%' 
       then city_name
       else null
       end),
       count(distinct case 
       when xs_code like '23%' or xs_code like '24%'       
       then  city_name
       else  null
      end)
  from tb_county 

查询结果是:

count(*)count(city_name)count(distinct city_name)count(casecount(distinct case
253425343638516

这个功能在统计中很有用,尤其是我们需要统计去重复的总量和分量的时候。

上面语句中的else还可以不写,因为默认情况下不写就是空值(null)。即:

select count(*),count(city_name),count(distinct city_name),
       count(case
               when xs_code like '23%' or xs_code like '24%' 
               then  city_name
             end),
       count(distinct case
               when xs_code like '23%' or xs_code like '24%' 
               then city_name
             end)
  from tb_county

————————————————

  • 6
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值