Case When可以用作select语句中的搜索,如果满足条件,就给字段附上结果值。
语法:
CASE WHEN '表达式1' THEN '结果1' WHEN '表达式2' THEN '结果2'WHEN '表达式3' THEN '结果3'ELSE '其他结果'
END
简单的例子:
当学生表tb_student里,gender=“1”,性别字段为“男”,gender=“0”,性别字段为“女”。
SELECT stu_code AS '学号',stu_name AS '学生姓名',(CASE WHEN gender=1 THEN '男'WHEN gender=0 THEN '女'ELSE '未知'END) AS '性别',grade AS '分数'
FROM tb_student;
通过sum函数汇总
举个例子,通过计算gender字段满足不同条件的累加值,计算男生人数和女生人数。
SELECT dep_code AS '部门编号',(CASE WHEN dep_code=10 THEN '总经办'WHEN dep_code=11 THEN '财务'WHEN dep_code=12 THEN '技术'WHEN dep_code=13 THEN '测试'WHEN dep_code=14 THEN '运维'ELSE '其他'END) AS '部门',SUM((CASE WHEN gender = 1 THEN 1 ELSE 0 END)) AS '男生人数',SUM((CASE WHEN gender = 0 THEN 1 ELSE 0 END)) AS '女生人数',COUNT(*) AS '部门总人数'
FROMtb_employee
GROUP BY dep_code;
参考博文
https://blog.csdn.net/Alian_1223/article/details/128253574