In the Oracle world, you can use:
1) case expression or
2) decode Function
To realize logical judgment. Oracle's DECODE function is very powerful. If you use it flexibly, you can avoid multiple scans to improve query performance. CASE is a syntax provided after 9i. This syntax is more flexible and provides the if then else function.
Case expression
A case expression can be divided into two types: simple and search. A simple case is followed by an expression, for example:
Pay attention to the following points for a simple case:
1) Priority of when search: top to bottom
2) when there are more when, there is only one exit, that is, if one of them meets expr, it will immediately exit the case.
3) return_expr and else_expr cannot be specified as null, and the Data Types of expr, comparison_expr, and return_expr must be the same.
Search case:
Case when condition THEN return_expr
[WHEN condition THEN return_expr]
...
ELSE else_expr
END
Example:
- SELECT(CASE WHENCust_credit_limitBETWEEN0AND3999THEN'0-3999'
- WHENCust_credit_limitBETWEEN4000AND7999THEN '2017-1000'
- WHENCust_credit_limitBETWEEN8000AND11999THEN'2017-1000'
- WHENCust_credit_limitBETWEEN12000AND16000THEN '2017-1000' END)
- ASBUCKET,COUNT(*)ASCount_in_Group
- FROMMERsWHERECust_city ='Marshal' GROUP BY
- (CASE WHENCust_credit_limitBETWEEN0AND3999THEN '0-3999'
- WHENCust_credit_limitBETWEEN4000AND7999THEN '2017-1000'
- WHENCust_credit_limitBETWEEN8000AND11999THEN'2017-1000'
- WHENCust_credit_limitBETWEEN12000AND16000THEN '2017-1000' END);
- BUCKET COUNT_IN_GROUP
- ---------------------------
- 0-3999 8
- 4000-7999 7
- 8000-11999 7
- 12000-16000 1
Decode can violate the 3NF (the row cannot be further divided, the column cannot be further divided, and the column cannot be repeated): The column is repeated.
- Hr @ ORCL>Select*FromA;
- IDNAME
- --------------------
- 1
- 2 B
- 3 c
- 1
- Hr @ ORCL>Select Sum(Decode (id, 1, 1, 0) think,
- 2Sum(Decode (id, 2, 2, 0) water,
- 3Sum(Decode (id, 3, 3, 0) linshuibin
- 4FromA;
- THINK WATER LINSHUIBIN
- ------------------------------
- 2 2 3