定义
CASE 函数允许在查询时判断设置判断条件, 根据判断条件,返回第一个值为true的结果。
如果没有条件符合,则执行ELSE语句的返回值,如果没有ELSE语句,则返回NULL
语法
CASE expression
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
WHEN conditionN THEN resultN
ELSE result
END
参数值
参数 | 描述 |
---|---|
expression | 可选,值将会与when的条件比较 |
condition1, condition2, …conditionN | 必须,按照列出的顺序与值比较,当有一个条件满足时,返回结果,返回的比较不再进行 |
result1, result2, …resultN | 必须,当条件为true时返回的结果 |
例子
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 something else"
END
FROM OrderDetails;
SELECT CustomerName, City, Country
FROM Customers
ORDER BY
(CASE
WHEN City IS NULL THEN Country
ELSE City
END);