那些年,我们一起使用过的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部分将会被自动忽略。

猜你喜欢

转载自blog.csdn.net/qq_44962429/article/details/107839714