gpt4 book ai didi

sql - 空结果集的聚合

转载 作者:行者123 更新时间:2023-11-29 11:15:36 26 4
gpt4 key购买 nike

我希望空结果集的聚合为 0。我尝试了以下操作:

SELECT SUM(COALESCE(capacity, 0))
FROM objects
WHERE null IS NOT NULL;

结果:

sum 
-----

(1 row)

子问题:如果使用 SUM(NVL(capacity, 0)),上面的内容不能在 Oracle 中运行吗?

最佳答案

来自 the documentation page关于聚合函数:

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. The coalesce function may be used to substitute zero for null when necessary.

因此,如果您想保证返回一个值,请将 COALESCE 应用于 SUM结果,而不是其参数:

SELECT COALESCE(SUM(capacity), 0) …

至于 Oracle“子问题”,嗯,我在官方文档页面(特别是 the one for 10.2)找不到任何 NULL 的概念,但另外两个来源是明确的:

也就是说,您不需要将 NVL 应用于容量。 (但是,与 PostgreSQL 中的 COALESCE 一样,您可能希望将其应用于 SUM。)

关于sql - 空结果集的聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6524352/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com