CASE命令用于根據(jù)條件創(chuàng)建不同的輸出。
以下SQL經(jīng)歷了幾種條件,并在滿足指定條件時(shí)返回一個(gè)值:
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)對(duì)客戶排序。但是,如果City為NULL,則按國(guó)家/地區(qū)(Country)排序:
SELECT CustomerName, City, Country FROM Customers ORDER BY (CASE WHEN City IS NULL THEN Country ELSE City END);