SQL Server 的聚合函数忽略空值。我该如何纠正?

end*_*ser 1 null sql-server aggregate

根据MS 的知识库

除了 COUNT,聚合函数忽略空值。

有谁知道我怎样才能让它正常工作,也就是说,如果它试图与值中的空值聚合,则返回空值?

例子:

SELECT SUM("col")
FROM (
    SELECT NULL "col"
    UNION
    SELECT 1 "col"
) test
Run Code Online (Sandbox Code Playgroud)

我希望这个查询返回NULL,而不是 1。

a_h*_*ame 9

您可以通过将 where 子句应用于您的查询来模拟这一点:

with test_data (col) as (
   select null union all 
   select 1 union all
   select 2
)
select sum(col)
from test_data
where not exists (select 1 
                  from test_data
                  where col is null);
Run Code Online (Sandbox Code Playgroud)

编辑

Andriy 是对的,这也可以写成:

with test_data (col) as (
   select null union all 
   select 1 union all
   select 2
)
select case 
          when count(*) = count(col) then sum(col)
          else null
       end
from test_data;
Run Code Online (Sandbox Code Playgroud)

  • 似乎有点矫枉过正。你可以只比较 `COUNT(col)` 和 `COUNT(*)`。 (2认同)