postgresql - 使用null排除任何结果

can*_*fus 4 sql postgresql

我正在做一堆求和查询: SELECT col1 + col2 + col3 + ...

某些列中的某些值为null.我正在检查它们

SELECT CASE WHEN col1 is not null and col2 is not null and ...
Run Code Online (Sandbox Code Playgroud)

我想知道是否有更简洁的语法来完成此任务.

小智 8

那么,既然任何数量的总和nullnull,你可以这样做以下(具有明显的...填写):

select big_honking_sum
from(
    select col1+col2+col3+...+coln as big_honking_sum
    from some_table
)sum
where big_honking_sum is not null;
Run Code Online (Sandbox Code Playgroud)


Joh*_*n P 6

如果您可以接受 NULL 值将被视为 0,请使用 COALESCE 函数。

SELECT COALESCE(Col1,0)
      + COALESCE(Col2,0)
      + COALESCE(Col3,0)
      AS TOTAL FROM table;
Run Code Online (Sandbox Code Playgroud)

如果适用的话,也许您可​​以考虑使用 0 作为默认值而不是 NULL。