那些年,我们一起使用过的case...when

1、case…when的用法

case具有两种用法,一种是case函数,另一种是case搜索函数
(1)第一种 格式 : 简单Case函数 :
格式说明:
    case 列名
    when 条件值1 then 选项1
    when 条件值2 then 选项2…
    else 默认值 end
示例:
    select
    case job_level
    when ‘1’ then ‘1111’
    when ‘2’ then ‘1111’
    when ‘3’ then ‘1111’
    else ‘’ end
    from employee
    
(2)第二种 格式 :Case搜索函数

格式说明
    case
    when 列名= 条件值1 then 选项1
    when 列名= 条件值2 then 选项2…
    else 默认值 end
eg:
    update employee
    set e_wage =
    case
    when job_level = ‘1’ then e_wage1.97
    when job_level = ‘2’ then e_wage
1.07
    when job_level = ‘3’ then e_wage1.06
    else e_wage
1.05
    end

2、使用案例

(1)根据以下数据,统计各个省份的人口数量
在这里插入图片描述

select case country
when '沈阳' then '辽宁'
when '铁岭' then '辽宁'
when '长春' then '吉林'
when '松原' then '吉林'
else '' end as 省份,
sum(population) as 数量
from test01
group by case country
when '沈阳' then '辽宁'
when '铁岭' then '辽宁'
when '长春' then '吉林'
when '松原' then '吉林'
else '' end

sql执行结果如下:
在这里插入图片描述
(2)根据某一列字段值,映射为另一值,并进行分组统计
在这里插入图片描述

select case when provinceID='1000' then '北京'
	  when provinceID='2000' then '辽宁'
      else '其他' end as 省份,
	  count(*) as 数据量
from test 
group by provinceID

sql运行结果如下:
在这里插入图片描述
(3)判断薪资等级的人数
在这里插入图片描述
*输出每个人的薪资等级

select name,
case when salary >1000 and salary<=2000 then '1000~2000'
	 when salary >2000 and salary<=3000 then '2000~3000'
	 else '其他' end as 薪资等级
from test02

sql执行结果
在这里插入图片描述
*进行每个等级的人数统计

select
case when salary >1000 and salary<=2000 then '1000~2000'
	 when salary >2000 and salary<=3000 then '2000~3000'
	 else '其他' end as 薪资等级,count(*)
from test02
group by 
case when salary >1000 and salary<=2000 then '1000~2000'
	 when salary >2000 and salary<=3000 then '2000~3000'
	  else '其他' end

sql执行结果
在这里插入图片描述
提示:通常我们在写Case When的语句的时候,会容易忘记 end 这个结束。

比较: 两种格式,可以实现相同的功能。

简单Case函数的写法相对比较简洁,但是和Case搜索函数相比,功能方面会有些限制,比如写判断式。还有一个需要注意的问题,Case函数只返回第一个符合条件的 值,剩下的Case部分将会被自动忽略。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值