SQL CASE 關鍵字
CASE
The CASE
command is used is to create different output based on conditions.
The following SQL goes through several conditions and returns a value when the specified condition is met
示例
SELECT OrderID, Quantity,
CASE
WHEN Quantity > 30 THEN '數量大於 30'
WHEN Quantity = 30 THEN '數量等於 30'
ELSE '數量小於 30'
END
FROM OrderDetails;
自己動手試一試 »
以下 SQL 語句將按城市對客戶進行排序。但是,如果城市為 NULL,則按國家排序
示例
SELECT CustomerName, City, Country
FROM Customers
ORDER BY
(CASE
WHEN City IS NULL THEN Country
ELSE City
END);
自己動手試一試 »