SQL CASE 关键字
CASE
CASE
命令用于根据条件创建不同的输出。
下面的SQL会遍历几个条件,当满足指定条件时返回一个值:
实例
SELECT OrderID, Quantity,
CASE
WHEN Quantity > 30
THEN "The quantity is greater than 30"
WHEN Quantity =
30 THEN "The quantity is 30"
ELSE "The quantity is
under 30"
END
FROM OrderDetails;
亲自试一试 »
以下 SQL 将按城市对客户进行排序。 但是,如果 City 为 NULL,则按 Country 排序:
实例
SELECT CustomerName, City, Country
FROM Customers
ORDER BY
(CASE
WHEN City IS NULL THEN Country
ELSE City
END);
亲自试一试 »