加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何检测PostgreSQL sum()中的NULL行

发布时间:2020-12-13 16:15:50 所属栏目:百科 来源:网络整理
导读:我想聚合列的总和,同时跟踪NULL值的存在,这些值表示错误情况.例如,取表号: # select * from numbers; n | l ------+----- 1 | foo 2 | foo NULL | bar 4 | bar 给定标签l,我想计算具有该标签的数字n的总和,前提是没有NULL值.理想情况下,对于没有任何行的标
我想聚合列的总和,同时跟踪NULL值的存在,这些值表示错误情况.例如,取表号:
# select * from numbers;
  n   |  l  
------+-----
    1 | foo
    2 | foo
 NULL | bar
    4 | bar

给定标签l,我想计算具有该标签的数字n的总和,前提是没有NULL值.理想情况下,对于没有任何行的标签,总和将为0.所以我正在寻找一些查询q
q(‘foo’)= 3,q(‘baz’)= 0并且q(‘bar’)以某种方式表示错误,例如通过返回NULL.

我从sum()aggregate function开始,但是将NULL行转换为0.一个解决方案是返回NULL的变量,前提是有任何NULL值.

sum()给出

# select sum(n) from numbers where l = 'bar';
 sum 
-----
   4

但我宁愿使用sumnull()

# select sumnull(n) from numbers where l = 'bar';
 sumnull 
---------
  NULL

到目前为止,我发现的最佳解决方案是计算非NULL行并与总计数进行比较:

# select sum(n),count(*),count(n) as notnull from numbers;
 sum | count | notnull 
-----+-------+---------
   7 |     4 |       3

然后,如果count不等于notnull,我知道结果无效.

空集是否足够好?
create table numbers (n int);
insert into numbers values (1),(2),(null),(4);

select sum(n)
from numbers
having bool_and(n is not null);
 sum 
-----
(0 rows)

如果你真的需要一个空值,它会有点复杂:

with sum_null as (
    select sum(n) as sum_n
    from numbers
    having bool_and(n is not null)
)
select case
    when not exists (select 1 from sum_null) then null
    else (select sum_n from sum_null) end
;
 sum_n 
-------

(1 row)

替换以下行:

having not bool_or(n is null)

可读性较差但可能更快,因为它可以在找到的第一个空值处停止搜索.

https://www.postgresql.org/docs/current/static/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读