Case
Calculates a list of conditions and returns one of several possible result expressions.
Case has two formats:
The simple case function compares an expression to a simple set of expressions to determine the result.
The case search function computes a set of Boolean expressions to determine the result.
Both formats support the optional else parameter.
Grammar
Simple Case function:
Case input_expression
When when_expression then result_expression
[... n]
[
else else_result_expression
End
Case Search Function:
Case
When Boolean_expression then result_expression
[... n]
[
else else_result_expression
End
For example, the following statement shows the Chinese month
Select GETDATE () as date, Case month (GETDATE ())
When one then ' 11 '
When then ' 12 '
else substring (' 1,234,567,890 ', Month (getdate ()), 1)
End+ ' Month ' as month
Take a look at the example below
Data table is demotable, field has ID, condition1,condition2,condition3,condition4,condition5
The requirement is to query demotable, condition1,condition2,condition3,condition4,condition5 Five fields that meet any of two or more than two conditions.
You can use case when to implement this condition, requiring nested subqueries
Examples of SQL statement code are as follows:
Copy code code as follows:
SELECT * FROM Demotable
Where (Select Case 1 when condition1 satisfies the condition then 1 else 0 end from demotable)
+ (Select Case 1 when condition2 satisfies the condition then 1 else 0 end from demotable)
+ (Select Case 1 when Condition3 satisfies the condition then 1 else 0 end from demotable)
+ (Select Case 1 when Condition4 satisfies the condition then 1 else 0 end from demotable)
+ (Select Case 1 when condition5 satisfies the condition then 1 else 0 end from demotable) >=2
The default return value type of a case expression is the compatible set type of any return value, but the situation depends on the context in which it resides. If used in a string context, the result flavour string is returned. If used in a numeric context, the result is a decimal value, a real value, or an integer value.
if (EXPR1,EXPR2,EXPR3)
If Expr1 is true (expr1 <> 0 and expr1 <> null), then the return value of if () is expr2; Otherwise, the return value is EXPR3. The return value of the IF () is a numeric value or a string value, depending on the context in which it is located.
MySQL Tutorials > Select if (1>2,2,3);
-> 3
Mysql> Select if (1<2, ' yes ', ' no ');
-> ' yes '
Mysql> Select if (strcmp (' Test ', ' test1 '), ' no ', ' yes ');
-> ' No '
In order to use case in the group by block, the query statement needs to repeat the case block in the Select block in the group by block.