我正在做一堆求和查询:
SELECT col1 + col2 + col3 + ...
一些列中的一些值是 null
。我正在通过以下方式进行检查:
SELECT CASE WHEN col1 is not null and col2 is not null and ...
我想知道是否有更简洁的语法来完成这个任务。
我正在做一堆求和查询:
SELECT col1 + col2 + col3 + ...
一些列中的一些值是 null
。我正在通过以下方式进行检查:
SELECT CASE WHEN col1 is not null and col2 is not null and ...
好的,既然任何数字和null
的总和都是null
, 那么你可以像下面这样做(显然需要填写...
):
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;
如果你可以接受NULL值被视为0,那么请使用COALESCE函数。
SELECT COALESCE(Col1,0)
+ COALESCE(Col2,0)
+ COALESCE(Col3,0)
AS TOTAL FROM table;
更简单、更快、更清晰:
... WHERE (col1, col2, col3) IS NOT NULL;
如果ROW expression中的所有字段都是NOT NULL
,则该表达式返回true
。请参见:
也可以应用于整个行:
SELECT ...
FROM my_table t
WHERE (t.*) IS NOT NULL;
num_nulls()
。在我对Postgres 15的测试中稍微昂贵一些,但更清晰:... WHERE num_nulls(col1, col2, col3) = 0;