ORACLE开发:Oracle中case when函数的用法
一、case when 的基本用法见:
二、case when在select语句中的用法
SELECT grade, COUNT (CASE WHEN sex = 1 THEN 1 ELSE NULL END) 男生数,
COUNT (CASE WHEN sex = 2 THEN 1 ELSE NULL END) 女生数
FROM students
GROUP BY grade;
COUNT (CASE WHEN sex = 2 THEN 1 ELSE NULL END) 女生数
FROM students
GROUP BY grade;
1、在Case函数中,可以使用BETWEEN,LIKE,IS NULL,IN,EXISTS等。
Case函数不同于DECODE函数。在Case函数中,可以使用BETWEEN,LIKE,IS NULL,IN,EXISTS等等。比如说使用IN,EXISTS,可以进行子查询,从而 实现更多的功能。
SELECT keyCol, CASE WHEN keyCol IN ( SELECT keyCol FROM tbl_B ) THEN ‘Matched’ ELSE ‘Unmatched’ END Label
FROM tbl_A;
FROM tbl_A;
也可以使用NOT IN和NOT EXISTS,但是这个时候要注意NULL的情况。
2、根据条件有选择的UPDATE。
UPDATE PersonnelSET salary =
CASE WHEN salary >= 5000 THEN salary * 0.9
WHEN salary >= 2000 AND salary < 4600 THEN salary * 1.15
ELSE salary END;
CASE WHEN salary >= 5000 THEN salary * 0.9
WHEN salary >= 2000 AND salary < 4600 THEN salary * 1.15
ELSE salary END;
三、case when在where语句中的用法
SELECT * FROM TB_Test
WHERE stateid IN ( 10, 20 )
AND ( CASE WHEN stateid = 20 AND userid <> 2 THEN 0
ELSE 1
END ) = 1
WHERE stateid IN ( 10, 20 )
AND ( CASE WHEN stateid = 20 AND userid <> 2 THEN 0
ELSE 1
END ) = 1
四、case when在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’
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’
ELSE NULL END;
CASE WHEN salary <= 500 THEN ‘1’
WHEN salary > 500 AND salary <= 600 THEN ‘2’
WHEN salary > 600 AND salary <= 800 THEN ‘3’
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’
ELSE NULL END;
到此这篇关于Oracle中case when函数用法的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持。