0

I have this statement here:

SELECT sum(table1.foo + table1.bar) AS Sum 
FROM table1
GROUP BY Fname;

When I try to add the numbers from foo and bar if one value from foo or bar is null it throws the numbers and gives me a different count sum

foo | bar
  6    4
  5    null
  9    1 
  2    1
  3    null

I want it to add all the numbers giving me a total of 31

but in this case it gives me a total of 23 Would love some help! Thanks!

3 Answers 3

2

Any Number + NULL = NULL. You want to indicate to the engine that when it sees a NULL, it should treat that NULL value as 0.

SELECT sum(ISNULL(table1.foo, 0) + ISNULL(table1.bar,0)) AS Sum 
FROM table1
GROUP BY Fname;
Sign up to request clarification or add additional context in comments.

Comments

1

Use coalesce():

SELECT sum(coalesce(table1.foo, 0) + coalesce(table1.bar, 0)) AS Sum 
FROM table1
GROUP BY Fname;

If you want the total, total on one row, remove the group by:

SELECT sum(coalesce(table1.foo, 0) + coalesce(table1.bar, 0)) AS Sum 
FROM table1;

Comments

-1

I believe you'll need to have SQL replace nulls with a zero using "ISNULL".

Try: SELECT sum(ISNULL(fix_bat_sum.foo, 0) + ISNULL(fix_bat_sum.bar, 0) ) AS Sum

1 Comment

Isn't ISNULL sql server specific? Maybe COALESCE would be better idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.