PostgreSQL CASE 表达式
CASE
The CASE
expression goes through conditions and returns a value when the first condition is met (like an if-then-else statement)。CASE
表达式会遍历条件,并在第一个条件满足时返回值(类似于 if-then-else 语句)。
Once a condition is true, it will stop reading and return the result. If no conditions are true, it returns the value in the ELSE
clause。一旦一个条件为真,它将停止读取并返回结果。如果没有条件为真,它将返回 ELSE
子句中的值。
如果没有 ELSE
部分且没有任何条件为真,则返回 NULL。
示例
Return specific values if the price meets a specific condition
当价格满足特定条件时返回特定值
SELECT product_name,
CASE
WHEN price < 10 THEN 'Low price product'
WHEN price > 50 THEN 'High price product'
ELSE
'Normal product'
END
FROM products;
运行示例 »
With an Alias
带别名
When a column name is not specified for the "case" field, the parser uses case
as the column name。如果未为“case”字段指定列名,则解析器将 case
用作列名。
To specify a column name, add an alias after the END
keyword。要指定列名,请在 END
关键字后添加别名。
示例
Same example, but with an alias for the case column:
与上面相同的示例,但为 case 列添加了别名:
SELECT product_name,
CASE
WHEN price < 10 THEN 'Low price product'
WHEN price > 50 THEN 'High price product'
ELSE
'Normal product'
END AS "price category"
FROM products;
运行示例 »
You can read more about aliases in our PostgreSQL AS chapter。您可以在我们的 PostgreSQL AS 章节 中了解更多关于别名的信息。