空结果集的集合 [英] aggregate of an empty result set
问题描述
我希望一个空结果集的总计为0。我尝试了以下操作:
I would like the aggregates of an empty result set to be 0. I have tried the following:
SELECT SUM(COALESCE(capacity, 0))
FROM objects
WHERE null IS NOT NULL;
结果:
sum
-----
(1 row)
子问题:使用 SUM(NVL(capacity,0))
能否在Oracle中完成以上工作?
Subquestion: wouldn't the above work in Oracle, using SUM(NVL(capacity, 0))
?
推荐答案
来自关于聚合函数的文档页面:
应注意的是,除了
count
,这些功能在未选择任何行时返回空值。特别是,没有行的sum
返回null,而不是预期的零。coalesce
函数可在必要时用于将零替换为null。
It should be noted that except for
count
, these functions return a null value when no rows are selected. In particular,sum
of no rows returns null, not zero as one might expect. Thecoalesce
function may be used to substitute zero for null when necessary.
因此,如果要保证返回的值,请将 COALESCE
应用于 SUM
结果 >,而不是它的论点:
So, if you want to guarantee a value returned, apply COALESCE
to the result of SUM
, not to its argument:
SELECT COALESCE(SUM(capacity), 0) …
关于Oracle的 subquestion,我在官方文档页面上找不到NULL的任何概念(特别是10.2版),但还有其他两个来源明确:
As for the Oracle 'subquestion', well, I couldn't find any notion of NULLs at the official doc page (the one for 10.2, in particular), but two other sources are unambiguous:
SUM([DISTINCT] n)
n的总和,忽略NULL
...如果在某些数字上创建了sum(),则空值会被忽略,如以下示例所示……
…if a sum() is created over some numbers, nulls are disregarded, as the following example shows…
是,您无需将NVL应用于 capability
。 (但是,就像在PostgreSQL中使用 COALESCE
一样,您可能希望将其应用于 SUM
。)
That is, you needn't apply NVL to capacity
. (But, like with COALESCE
in PostgreSQL, you might want to apply it to SUM
.)
这篇关于空结果集的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!