57.Oracle数据库SQL开发之 高级查询——使用CASE函数
欢迎转载,转载请标明出处:http://blog.csdn.net/notbaron/article/details/49847013
CASE表达式可以再SQL中实现if-then-else型的逻辑,9i及以上版本支持CASE表达式。
1. 使用简单CASE表达式
语法如下:
CASE search_expression
WHENexpression1 THEN result1
…
ELSEdefault_result
END
store@PDB1> select product_id,product_type_id,caseproduct_type_id
when 1 then'book'
when 2 then'video'
when 3 then'dvd'
when 4 then'cd'
else'Magazine'
end
fromproducts;
PRODUCT_ID PRODUCT_TYPE_ID CASEPROD
---------- --------------- --------
1 1 book
2 1 book
3 2 video
4 2 video
5 2 video
6 2 video
7 3 dvd
8 3 dvd
9 4 cd
10 4 cd
11 4 cd
12 Magazine
12 rows selected.
2. 使用搜索CASE表达式
搜索CASE表达式使用条件确定返回值,语法如下:
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
…
ELSE default_result
END
执行如下:
store@PDB1>select product_id,product_type_id,
case
when product_type_id=1 then 'book'
when product_type_id=2 then 'video'
when product_type_id=3 then 'dvd'
when product_type_id=4 then 'cd'
else 'Magazine'
end
from products;
PRODUCT_IDPRODUCT_TYPE_ID CASEWHEN
------------------------- --------
1 1 book
2 1 book
3 2 video
4 2 video
5 2 video
6 2 video
7 3 dvd
8 3 dvd
9 4 cd
10 4 cd
11 4 cd
12 Magazine
12 rows selected.