我想聚合列的总和,同时跟踪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,我知道结果无效.
空集是否足够好?
原文链接:https://www.f2er.com/postgresql/192003.htmlcreate 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