case when 是mySQL里面的控制流语句。case when语句有两种:
(1)简单case when
(2)case搜索函数法
下面结合实验课内容简单介绍:
先建立两个表:
emp_sex,包含员工姓名,员工部门,性别
person_info,包含员工姓名,星座,血型
表数据:
用case when 查询每个部门的男生女生人数:
select dept_id,
sum(case sex when 'man' then 1 else 0 end) male_count,
sum(case sex when 'woman'then 1 else 0 end) female_count
from emp_sex1
group by dept_id;
查询结果:
再比如:
查询每种血型中白羊座、射手座 的人数:
select blood_type,
sum(case xingzuo when 'baiyang' then 1 else 0 end) type_A,
sum(case xingzuo when 'sheshou' then 1 else 0 end) type_B
from person_info
group by blood_type;
查询结果: