SQL Server – How to Correct Aggregate Functions Ignoring NULLs

aggregatenullsql server

According to MS's knowledgebase,

Except for COUNT, aggregate functions ignore null values.

Does anyone know how I can get it to work correctly, that is, return a null if it attempts to aggregate with a null in the values?

Example:

SELECT SUM("col")
FROM (
    SELECT NULL "col"
    UNION
    SELECT 1 "col"
) test

I would expect this query to return NULL, not 1.

Best Answer

You can simulate this by applying a where clause to your query:

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);

Edit

Andriy is right, this can also be written as:

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;