1

I would like to know how can I add up the result of my subqueries within a table. For example, I want to add up the following two queries in one statement.

SELECT SUM(A) - (SELECT SUM(B) FROM MyTable WHERE C<A))
FROM MyTable WHERE B>C;

SELECT SUM(B) - (SELECT SUM(C) FROM MyTable WHERE D<F))
FROM MyTable WHERE B=C;
1
  • Could you provide real column names or some kind of fake schema that helps us to make sense of why you're doing this? Sometimes it's easier to come up with answers when there is an analogical model to relate to. Why does it make sense to do these weird column comparisons and summing/subtracting?
    – ErikE
    Commented Jun 12, 2013 at 17:15

1 Answer 1

3

You can literally just add them together:

SELECT (SELECT SUM(A) - (SELECT SUM(B) FROM MyTable WHERE C<A))
                         FROM MyTable WHERE B>C)  
        +
        (SELECT SUM(B) - (SELECT SUM(C) FROM MyTable WHERE D<F))
                          FROM MyTable WHERE B=C)

Same as:

SELECT 5 + 3

You could also probably use some CASE statements to do this without the subqueries, or to make it cleaner at the least, something like:

SELECT SUM(CASE WHEN B > C THEN A ELSE 0 END) - SUM(CASE WHEN C < A THEN B ELSE 0 END)
       +
       SUM(CASE WHEN B = C THEN B ELSE 0 END) - SUM(CASE WHEN D < F THEN C ELSE 0 END)
FROM MyTable
6
  • fantastic! Simple and helpful
    – nec tso
    Commented Jun 12, 2013 at 17:33
  • @Goat_CO . . . You fixed the query since my comment. My point directed at the OP about accepting an answer that wasn't correct than on your response. If the previous version was correct, s/he should have explained why. Commented Jun 12, 2013 at 17:55
  • Hmm, I thought the only edits were for wording and adding the CASE Statement portion. No problem either way.
    – Hart CO
    Commented Jun 12, 2013 at 18:00
  • @Goat_CO The result is null, how can I show that it's 0 (zero) ? Thanks!
    – nec tso
    Commented Jun 12, 2013 at 18:41
  • 1
    SELECT ISNULL(field,0) + ISNULL(field2,0). ISNULL returns whatever you put after the comma if the field is NULL. COALESCE is similar, returns first non-NULL value from the set of values you give it. If NULL's are giving you fits then you can wrap each one in an ISNULL/COALESCE statement.
    – Hart CO
    Commented Jun 12, 2013 at 19:31

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.