Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

PostgreSQL CASE 表达式


CASE

The CASE 表达式遍历条件,并在第一个条件满足时返回一个值(类似于 if-then-else 语句)。

一旦某个条件为真,它将停止读取并返回结果。如果没有任何条件为真,则返回 ELSE 子句中的值。

如果没有 ELSE 部分且没有任何条件为真,则返回 NULL。

示例

如果价格满足特定条件,则返回特定值

SELECT product_name,
CASE
  WHEN price < 10 THEN '低价产品'
  WHEN price > 50 THEN '高价产品'
ELSE
  '普通产品'
END
FROM products;
运行示例 »

使用别名

当没有为“case”字段指定列名时,解析器将使用 case 作为列名。

要指定列名,请在 END 关键字后添加别名。

示例

相同的示例,但为 case 列添加了别名:

SELECT product_name,
CASE
  WHEN price < 10 THEN '低价产品'
  WHEN price > 50 THEN '高价产品'
ELSE
  '普通产品'
END AS "价格类别"
FROM products;
运行示例 »

您可以在我们的 PostgreSQL AS 章节 中阅读更多关于别名的信息。


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.