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 章節 中瞭解更多關於別名的資訊。