SQL CASE
语句评估一系列条件,并根据条件添加一列值。例如:
-- add a new column 'order_volume' in the Orders table
-- and flag any order greater than 10000 as 'Large Order'
-- and smaller than 10000 as 'Small Order'
SELECT *,
CASE
WHEN amount >= 10000 THEN 'Large Order'
WHEN amount < 10000 THEN 'Small Order'
END AS 'order_volume'
FROM Orders;
这里,结果集中有一个新列 order_volume,它将金额大于或等于 10000 的行标记为 Large Order
,将小于 10000 的行标记为 Small Order
。
SQL CASE 语法
SELECT column1, column2,... ,
CASE
WHEN condition THEN result
END AS alias_name
FROM table;
这里,
- column1,column2, ... 是要包含在结果集中的列名
CASE
检查condition
- 如果满足
condition
,result
是要插入到新列中的结果或值 END
结束CASE
语句AS
为新列指定名称alias_name
- table 是表的名称。
注意:CASE
的语法总是以 CASE
关键字开头,以 END
关键字结尾,后面跟着一个列名别名。
示例:使用 SQL CASE 进行选民资格判断
-- add a new column 'can_vote' to Customers table
-- insert 'Allowed' into it if customer is older than 17
SELECT customer_id, first_name,
CASE
WHEN age >= 18 THEN 'Allowed'
END AS can_vote
FROM Customers;
这里,SQL 命令根据给定的情况检查每一行。结果集包含
- customer_id 和 first_name 列中的值
- 一个新的 can_vote 列,如果年龄大于 18,则值为
Allowed
,否则为空

示例:SQL CASE 计算折扣金额
我们来看另一个例子,我们想在圣诞节促销期间为每个订单提供 10% 的折扣,如果金额为 400 或更多。
SELECT order_id, customer_id,
CASE
WHEN amount >= 400 THEN (amount - amount * 10/100)
END AS offer_price
FROM Orders;
这里,CASE
语句检查 amount 是否大于或等于 400。如果满足此条件,则新列 offer_price 将包含等于 amount - amount * 10/100
的值。
CASE 与多个条件
也可以在单个 CASE
子句中堆叠多个条件。
语法
SELECT column1, column2, ...
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
-- Add more WHEN conditions and results as needed
END AS alias_name
FROM table_name;
我们可以在 CASE
语句中根据需要添加任意数量的 WHEN ... THEN
条件。例如:
-- multiple CASE conditions in SQL
SELECT customer_id, first_name,
CASE
WHEN country = 'USA' THEN 'United States of America'
WHEN country = 'UK' THEN 'United Kingdom'
END AS country_name
FROM Customers;
这里,结果集包含一个新列 country_name 以及 customer_id 和 first_name。
country_name 的值变为
- 如果 country 等于 USA,则为 United States of America
- 如果 country 等于 UK,则为 United Kingdom
CASE 与 ELSE
CASE
语句可以有一个可选的 ELSE
子句。如果 CASE
语句中的任何条件都不匹配,则执行 ELSE
子句。
语法
SELECT customer_id, first_name,
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
-- Add more WHEN conditions and results as needed
ELSE else_result
END AS alias_name
FROM table_name;
ELSE
子句没有条件,因为它在没有 WHEN
条件匹配时执行。例如:
-- CASE condition with ELSE clause in SQL
SELECT customer_id, first_name,
CASE
WHEN country = 'USA' THEN 'United States of America'
WHEN country = 'UK' THEN 'United Kingdom'
ELSE 'Unknown Country'
END AS country_name
FROM Customers;
这里,结果集包含一个新列 country_name 以及 customer_id 和 first_name。
country_name 的值变为
- 如果 country 是 USA,则为 United States of America
- 如果 country 是 UK,则为 United Kingdom
- 如果 country 既不是 USA 也不是 UK(因为
ELSE
子句),则为 Unknown Country。
