CASE函数经常看到,COALESCE不怎么用到,但好像在别人的代码中看到过。今天学习一下。
---------------------------------------------------------------------------------------------------------------------
COALESCE
Syntax
Purpose
COALESCE returns the first non-null expr in the expression list. You must specify at least
two expressions. If all occurrences of expr evaluate to null, then the function returns
null.
Oracle Database uses short-circuit evaluation. The database evaluates each expr value
and determines whether it is NULL, rather than evaluating all of the expr values before
determining whether any of them is NULL.
If all occurrences of expr are numeric data type or any nonnumeric data type that can
be implicitly converted to a numeric data type, then Oracle Database determines the
argument with the highest numeric precedence, implicitly converts the remaining
arguments to that data type, and returns that data type.
This function is a generalization of the NVL function.
You can also use COALESCE as a variety of the CASE expression. For example,
COALESCE(expr1, expr2)
is equivalent to:
CASE WHEN expr1 IS NOT NULL THEN expr1 ELSE expr2 END
Similarly,
COALESCE(expr1, expr2, ..., exprn)
where n >= 3, is equivalent to:
CASE WHEN expr1 IS NOT NULL THEN expr1
ELSE COALESCE (expr2, ..., exprn) END
Examples
The following example uses the sample oe.product_information table to organize a
clearance sale of products. It gives a 10% discount to all products with a list price. If
there is no list price, then the sale price is the minimum price. If there is no minimum
price, then the sale price is "5":
SELECT product_id, list_price, min_price,
COALESCE(0.9*list_price, min_price, 5) "Sale"
FROM product_information
WHERE supplier_id = 102050
ORDER BY product_id;
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-40 for more information on implicit conversion and "Numeric
Precedence" on page 3-14 for information on numeric precedence
See Also: NVL on page 5-173 and "CASE Expressions" on page 6-5
COALESCE
PRODUCT_ID LIST_PRICE MIN_PRICE Sale
---------- ---------- ---------- ----------
1769 48 43.2
1770 73 73
2378 305 247 274.5
2382 850 731 765
3355 5

本文详细介绍了COALESCE函数的语法、用途及如何在数据库查询中使用它来返回表达式列表中的第一个非空值。通过实例展示了COALESCE函数如何在折扣销售场景中灵活运用,以确定产品的销售价格。
&spm=1001.2101.3001.5002&articleId=83388942&d=1&t=3&u=1f651424091447809f0840b80ae59b7c)
1623

被折叠的 条评论
为什么被折叠?



