SQL CASE 关键字

CASE

CASE 命令用于根据条件创建不同的输出。

以下 SQL 经过几个条件,并在满足指定条件时返回一个值:

实例
  1. SELECT OrderID, Quantity,
  2. CASE
  3. WHEN Quantity > 30 THEN "The quantity is greater than 30"
  4. WHEN Quantity = 30 THEN "The quantity is 30"
  5. ELSE "The quantity is under 30"
  6. END
  7. FROM OrderDetails;

以下 SQL 将按城市对客户进行排序。但是,如果城市为空,则按国家排序:

实例
  1. SELECT CustomerName, City, Country
  2. FROM Customers
  3. ORDER BY
  4. (CASE
  5. WHEN City IS NULL THEN Country
  6. ELSE City
  7. END);

分类导航