今天向大家介绍oracle数据库中 case when 语句的用法详解,主要包括它的用法详解、使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值。
CASE WHEN 表达式有两种形式
1 --简单Case函数 2 3 CASE sex 4 WHEN '1' THEN '男' 5 WHEN '2' THEN '女' 6 ELSE '其他' END 7 8 --Case搜索函数 9 10 CASE 11 WHEN sex = '1' THEN '男' 12 WHEN sex = '2' THEN '女' 13 ELSE '其他' ENDView Code
CASE WHEN 在语句中不同位置的用法
1.在SELECT后面的用法(目标显示结果中)
SELECT grade, COUNT (CASE WHEN sex = 1 THEN 1 /*sex 1为男生,2位女生*/ ELSE NULL END) 男生数, COUNT (CASE WHEN sex = 2 THEN 1 ELSE NULL END) 女生数 FROM students GROUP BY grade;
注:此语句表示查询学生信息表中各年级的男生和女生数,并按年级分组(数据库中性别是以1和2表示)
2.在WHERE 后 用法(作为条件进行)
1 SELECT T2.*, T1.* 2 FROM T1, T2 3 WHERE (CASE WHEN T2.COMPARE_TYPE = 'A' AND 4 T1.SOME_TYPE LIKE 'NOTHING%' 5 THEN 1 6 WHEN T2.COMPARE_TYPE != 'A' AND 7 T1.SOME_TYPE NOT LIKE 'NOTHING%' 8 THEN 1 9 ELSE 0 10 END) = 1
注:
3.GROUP BY 后的用法(分组条件中)
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;
标签:case,salary,END,when,WHEN,CASE,用法,oracle,sex From: https://www.cnblogs.com/lsxs-wy/p/17773463.html