本文共 1756 字,大约阅读时间需要 5 分钟。
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_wage1.07 when job_level = ‘3’ then e_wage1.06 else e_wage1.05 end(1)根据以下数据,统计各个省份的人口数量
select case countrywhen '沈阳' then '辽宁'when '铁岭' then '辽宁'when '长春' then '吉林'when '松原' then '吉林'else '' end as 省份,sum(population) as 数量from test01group by case countrywhen '沈阳' 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执行结果
*进行每个等级的人数统计selectcase when salary >1000 and salary<=2000 then '1000~2000' when salary >2000 and salary<=3000 then '2000~3000' else '其他' end as 薪资等级,count(*)from test02group 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部分将会被自动忽略。
转载地址:http://dimzi.baihongyu.com/