0

I am building an application that uses a SQL statement to sum three columns. Below is a sample table:

Table1
column1     column2  column3
NULL        30.00    NULL
60.00       NULL     NULL
NULL        10.00    NULL
NULL        NULL     15.00

I want to sum column1, column2, and column3 into one statement. I want the result to be 115.00 (30.00 + 60.00 + 10.00 + 15.00). The table can have data in one of the three columns, but never in any two.

This is what I have so far:

SELECT ISNULL(sum(column1),ISNULL(sum(column2),sum(column3)) as amount FROM Table1

The result is something not remotely close.

1

3 Answers 3

1

In your case, you can do:

select sum(column1) + sum(column2) + sum(column3)
from table1 t;

Because each column has at least one value, the individual sums will not be NULL, so this will give the expected value.

To be safe, you could use coalesce():

select coalesce(sum(column1), 0) + coalesce(sum(column2), 0) + coalesce(sum(column3), 0)
from table1 t;
Sign up to request clarification or add additional context in comments.

Comments

1

Use coalesce to assign 0 when there is null in the column and then sum the values.

SELECT SUM(coalesce(column1,0)+coalesce(column2,0)+coalesce(column3,0)) as amount 
FROM Table1

Comments

1

The COALESCE function will also work. In the given example:

SELECT sum(COALESCE(column1,0))
          + COALESCE(column2,0)
          + COALESCE(column3,0)
    AS TOTAL FROM Table1

Comments

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.