case函数 有两种格式。简单case函数和case搜索函数。
https://blog.csdn.net/love_java_cc/article/details/52234415
case函数只返回第一个符合条件的值,剩下的case部分将会被自动忽略
意识就是,只要前面的when满足了那就返回对应的then不会继续往下执行,类似if/else,而不是switch(会穿透)
比如说,下面这段sql,你永远无法得到“第二类”这个结果
case when col_1 in ( 'a', 'b') then'第一类'
when col_1 in ('a') then '第二类'
else '其他' end
简单case函数
case sex
when '1' then '男'
when '2' then '女’
else '其他' end
case搜索函数
case when sex = '1' then '男'
when sex = '2' then '女'
else '其他' end
可以和关键字连用
比如in
SELECT a.managecom,
a.subtype,
count(*) loadsucc,
sum(case when a.state in ('4', '5', '6', '7', '8', '9') then 1 else 0 end) recogsucc,
sum(case when a.state in ('3', '12', '13') then 1 else 0 end) recogfail,
sum(case when a.state in ('1', '2') then 1 else 0 end) waitrecog
FROM ocr_docdetail a, ocr_loaddetail c
可以和其他函数连用
比如sum()函数
select
sum(case u.sex when 1 then 1 else 0 end) 男性,
sum(case u.sex when 2 then 1 else 0 end) 女性,
sum(case when u.sex <>1 and u.sex<>2 then 1 else 0 end)性别为空
from users u;
比如count()函数
select
count(case when u.sex=1 then 1 end)男性,
count(case when u.sex=2 then 1 end)女,
count(case when u.sex <>1 and u.sex<>2 then 1 end)性别为空
from users u;
比如group by,实现分组的功能
步骤:先再select后面分组,再同样的分组再group by后面子再来一次
例子一:实现把国家按照州分组,然后求各个州的人口总和
select sum(population),
case country
when '中国' then'亚洲'
when '印度' then'亚洲'
when '日本' then'亚洲'
when '美国' then'北美洲'
when '加拿大' then'北美洲'
when '墨西哥' then'北美洲'
else '其他' end
from table_a
group by case country
when '中国' then'亚洲'
when '印度' then'亚洲'
when '日本' then'亚洲'
when '美国' then'北美洲'
when '加拿大' then'北美洲'
when '墨西哥' then'北美洲'
else '其他' end;
例子二:薪水分组
select
case when salary <= 500 then '1'
when salary > 500 and salary <= 600 then '2'
when salary > 600 and salary <= 800 then '3'
when salary > 800 and salary <= 1000 then '4'
else null end salary_class,
count(*)
from table_a
group by
case when salary <= 500 then '1'
when salary > 500 and salary <= 600 then '2'
when salary > 600 and salary <= 800 then '3'
when salary > 800 and salary <= 1000 then '4'
else null end;
例子三:按照国家和性别分组
select country,
sum( case when sex = '1' then
population else 0 end), --男性人口
sum( case when sex = '2' then
population else 0 end) --女性人口
from table_a
group by country;