2

I have result of two queries like:

Result of query 1

ID   Value
1    4
2    0
3    6
4    9

Result of query 2

ID   Value
1    6
2    4
3    0
4    1

I want to add values column "Value" and show final result:

Result of Both queries

ID   Value
1    10
2    4
3    6
4    10

plz guide me...

0

3 Answers 3

3
select id, sum(value) as value
from (
    select id, value from query1
    uninon all
    select id, value from query2
) x
group by id
Sign up to request clarification or add additional context in comments.

Comments

0

Try using a JOIN:

SELECT
    T1.ID,
    T1.Value + T2.Value AS Value
FROM (...query1...) AS T1
JOIN (...query2...) AS T2
ON T1.Id = T2.Id

You may also need to consider what should happen if there is an Id present in one result but not in the other. The current query will omit it from the results. You may want to investigate OUTER JOIN as an alternative.

2 Comments

+1: I'm glad that you removed the answer. Feel as though our generousity is sometimes abused.
@Ardman: "generousity[sic]"? How dare you?! Most of us are here to exercise our egos! ;)
0

A not particularly nice but fairly easy to comprehend way would be:

SELECT ID,SUM(Value) FROM
(
(SELECT IDColumn AS ID,ValueColumn AS Value FROM TableA) t1
OUTER JOIN
(SELECT IDColumn AS ID,ValueColumn AS Value FROM TableB) t2
) a GROUP BY a.ID

It has the benefits of

a) I don't know your actual table structure so you should be able to work out how to get the two 'SELECT's working from your original queries b) If ID doesn't appear in either table, that's fine

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.