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)对客户排序。但是,如果City为NULL,则按国家/地区(Country)排序:
SELECT CustomerName, City, Country FROM Customers ORDER BY (CASE WHEN City IS NULL THEN Country ELSE City END);