How to return null when summing values that include nulls

cricketbird

Registered User.
Local time
Today, 14:14
Joined
Jun 17, 2013
Messages
111
Currently, if my data in a given column is: (1, 2, 3, 4, 5, (missing), 7, 8, 9), then when I sum these I get 39, whereas I want to get NULL because in my business case I can't sum these values if I don't have all these values. I don't want to return a partial sum.

So, in a simple query, I'd have:

SQL:
SELECT Sum([MyColumn]) AS [SumOfMyColumn]
FROM MyTable;

How do I get it to return NULL if there is missing data?

(if anyone uses R, I'm trying to do: sum(x, na.rm = FALSE)
 
Last edited:
This is going to take a subquery to determine if there are any nulls:

Code:
SELECT Min(IsNull([MyColumn])) AS HasNulls, Sum(MyColumn) AS ColumnSum
FROM YourTable;

Then make a query on that and use HasNulls to determine what to return:

Code:
SELECT IIF(HasNulls=False, ColumnSum) AS YourSum
FROM ThatQuery
 
This is going to take a subquery to determine if there are any nulls:

Code:
SELECT Min(IsNull([MyColumn])) AS HasNulls, Sum(MyColumn) AS ColumnSum
FROM YourTable;

Then make a query on that and use HasNulls to determine what to return:

Code:
SELECT IIF(HasNulls=False, ColumnSum) AS YourSum
FROM ThatQuery
Thanks! It makes sense - I will give it a whirl in the morning :)
 
You can also do this...
SQL:
SELECT IIf(Sum([MyColumn] Is Null), Null, Sum([MyColumn])) AS MyColumnSum
FROM tMyTable;
If one or more rows have nulls, this expression: Sum([MyColumn] Is Null) is true, so return a Null, otherwise return the complete sum.
 
You can also do this...
SQL:
SELECT IIf(Sum([MyColumn] Is Null), Null, Sum([MyColumn])) AS MyColumnSum
FROM tMyTable;
If one or more rows have nulls, this expression: Sum([MyColumn] Is Null) is true, so return a Null, otherwise return the complete sum.
I wanted this to work, and it seems like it should, but I still get values and not NULLs as the sum when I do this. I'll keep playing around with this...
 
If you want more help, show your exact code/SQL etc...

Remember, if in a particular row a field like [MyColumn] is null, then the boolean expression "[MyColumn] Is Null" evaluates to -1 (True) for that row. If we then Sum() that expression, we get a (negated) count of null rows.

The bracketing and parenthesis make a HUGE difference. This, for instance, will fail...
Code:
SELECT IIF(Sum([MyColumn]) Is Null, Null, Sum([MyColumn]))
This will work...
Code:
SELECT IIF(Sum([MyColumn] Is Null), Null, Sum([MyColumn]))
 
You can try this variation:
SQL:
SELECT
  IIf(
    DCount('*', 'tMyTable', [MyColumn] Is Null) > 0,
    Null,
    Sum([MyColumn]
  ) AS MyColumnSum
FROM tMyTable;
 

Users who are viewing this thread

Back
Top Bottom