case when sql
时间: 2023-10-06 08:07:41 浏览: 82
CASE WHEN is a conditional statement in SQL that allows you to perform different actions based on specified conditions. It is typically used in conjunction with the SELECT statement to add conditional logic to the result set.
Here's an example of how you can use the CASE WHEN statement in SQL:
```sql
SELECT column1, column2,
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
ELSE result3
END AS alias
FROM your_table;
```
In this example, you specify the conditions and corresponding results within the CASE WHEN statement. If condition1 is true, it will return result1. If condition2 is true, it will return result2. If none of the conditions are true, it will return result3.
You can also use the CASE WHEN statement without any conditions, which acts like an IF-ELSE statement:
```sql
SELECT column1, column2,
CASE
WHEN value = 1 THEN 'One'
ELSE 'Not One'
END AS alias
FROM your_table;
```
In this case, if the value is equal to 1, it will return 'One'. Otherwise, it will return 'Not One'.
阅读全文