SQL中case when
时间: 2023-10-17 13:30:48 浏览: 94
case when语句在SQL中用于根据条件执行不同的操作或返回不同的值。它的语法如下:
```
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
ELSE result
END
```
其中,condition1、condition2等是条件表达式,result1、result2等是相应条件满足时的返回值。ELSE子句是可选的,用于指定当所有条件都不满足时的默认返回值。
这个语句可以嵌套在其他SELECT、UPDATE或DELETE语句中使用,也可以用于计算列或作为查询结果的一部分。
请告诉我还有什么问题我可以帮助你解答。
相关问题
SQL中CASE WHEN
### SQL CASE WHEN 语句解析
#### 简单 CASE WHEN 语句
简单 `CASE` 表达式的结构如下:
```sql
CASE input_expression
WHEN when_expression_1 THEN result_expression_1
...
[ELSE else_result_expression]
END
```
此形式适用于当测试多个可能的结果是否等于某个单一表达式时。例如,如果想要将成绩转换成文字描述,则可以这样写[^1]。
#### 搜索条件 CASE WHEN 语句
更常见的 `CASE` 形式是带有搜索条件的形式,它可以更加灵活地定义各种逻辑判断标准:
```sql
CASE
WHEN condition_1 THEN result_1
...
[ELSE else_result]
END
```
这种情况下,不是比较两个值之间的相等关系,而是评估布尔表达式来决定执行哪一部分代码[^4]。
#### 实际案例展示
考虑一个场景,在学生评分表中存在分数字段 `score` ,现在希望基于这些数值生成一个新的等级列 `grade` 。可以通过以下方式完成这一操作:
```sql
SELECT name, score,
CASE
WHEN score >= 90 THEN '优秀'
WHEN score BETWEEN 80 AND 89 THEN '良好'
WHEN score BETWEEN 70 AND 79 THEN '一般'
ELSE '不合格'
END AS grade
FROM students;
```
上述查询会根据学生的具体得分给予相应的评价标签[^3]。
#### 使用 CASE WHEN 进行分组统计
除了在选择列表里构建新列外,还可以利用 `CASE` 在聚合函数内实施分类汇总工作。比如按照性别区分平均工资水平:
```sql
SELECT AVG(CASE gender WHEN 'M' THEN salary END) as male_avg_salary,
AVG(CASE gender WHEN 'F' THEN salary END) as female_avg_salary
FROM employees;
```
这里通过 `GROUP BY` 和 `CASE` 的组合实现了按不同类别分别求均值的效果[^2]。
sql中case when
在SQL中,CASE WHEN语句用于根据满足指定条件时执行不同的操作。它的语法如下:
```
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
ELSE result
END
```
这里的condition1,condition2等是要满足的条件,result1,result2等是根据条件的结果。
下面是一个示例,演示如何在SQL中使用CASE WHEN语句:
假设我们有一个名为employees的表,其中包含员工的姓名和薪水。如果员工的薪水超过10000,则将其职级设置为高级,否则设置为普通。
```sql
SELECT
name,
salary,
CASE
WHEN salary > 10000 THEN '高级'
ELSE '普通'
END AS 职级
FROM employees;
```
输出将包含姓名、薪水和职级三列,其中职级根据薪水是否超过10000进行判断。
阅读全文
相关推荐
















