case+when.+Pgsql
时间: 2024-02-02 16:03:55 浏览: 166
在Pgsql中,CASE WHEN语句用于进行条件判断和赋值。以下是一个示例代码:
```sql
SELECT column1, column2,
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
WHEN conditionN THEN resultN
ELSE result
END AS new_column
FROM table_name;
```
在上述代码中,column1和column2是要选取的原始字段,condition1、condition2等是条件表达式,result1、result2等是对应条件满足时的赋值结果,new_column是赋值后的结果字段名,table_name是要查询的表名。
相关问题
pgsql case when
在 PostgreSQL 中,CASE WHEN 是一种条件表达式,用于根据不同的条件返回不同的结果。它的语法如下:
```
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
ELSE result
END
```
其中,condition1、condition2等是条件表达式,result1、result2等是对应条件为真时返回的结果。ELSE 子句是可选的,用于指定当所有条件都不满足时的默认返回结果。
CASE WHEN 可以嵌套使用,形成复杂的条件判断逻辑。例如:
```
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN
CASE
WHEN sub_condition1 THEN sub_result1
WHEN sub_condition2 THEN sub_result2
...
ELSE sub_result
END
...
ELSE result
END
```
这样可以根据不同的条件组合返回不同的结果。
相关问题:
1. PostgreSQL 中的 CASE WHEN 语句的语法是什么?
2. CASE WHEN 可以嵌套使用吗?
3. CASE WHEN 的作用是什么?
pgsql case when示例
在 PostgreSQL 中,CASE WHEN 表达式是一种条件语句,用于根据一个或多个条件执行不同的操作。以下是 CASE WHEN 表达式的示例:
```
SELECT
name,
grade,
CASE
WHEN grade >= 90 THEN 'A'
WHEN grade >= 80 THEN 'B'
WHEN grade >= 70 THEN 'C'
WHEN grade >= 60 THEN 'D'
ELSE 'F'
END AS letter_grade
FROM
students;
```
在上面的示例中,我们使用 CASE WHEN 表达式将学生的分数转换为字母等级(A、B、C、D、F)。对于每个学生,我们检查他们的分数,并根据其值执行相应的操作。
阅读全文
相关推荐
















