CASE WHEN THEN ELSE END与If的使用案例
1、数据准备:
2、需求:
求出不同部门男女各多少人。结果如下:
dept_Id 男 女 A 2 1 B 1 2select
dept_id,
sum(case sex when '男' then 1 else 0 end) maleCount,
sum(case sex when '女' then 1 else 0 end) femaleCount
from
emp_sex
group by
dept_id;
select
dept_id,
sum(if(sex = '男', 1, 0)) maleCount,
sum(if(sex = '女', 1, 0)) femaleCount
from
emp_sex
group by
dept_id;