Reputation: 25
I am trying to grab the sum of the same variable under two different conditions. Just wondering if there is a way to get these added together. The details of the queries aren't really too relevant. Basically just trying to take the first sum and add it with the second sum.
For Example --
First Query :
select sum(amt_tot)
from agbgift, aprdclb
where agbgift_id = '1' and agbgift_id = aprdclb_id
Second Query :
select sum(amt_tot)
from agbgift, aprxref, aprdclb where
aprxref_id = '1' and
agbgift_id = aprxref_xref_id and
aprxref_id = aprdclb_id and
xref_code in ('SPS','BUS','ORG','OWN','FDN' );
The end result i am looking for is 'First Query Sum' + 'Second Query Sum'
Upvotes: 0
Views: 7619
Reputation: 116190
In this case, it's as simple as this:
SELECT
/* Query 1 (in parentheses) */
(select sum(amt_tot)
from agbgift, aprdclb
where agbgift_id = '1' and agbgift_id = aprdclb_id)
+ /* plus */
/* Query 2 (also in parentheses) */
(select sum(amt_tot)
from agbgift, aprxref, aprdclb where
aprxref_id = '1' and
agbgift_id = aprxref_xref_id and
aprxref_id = aprdclb_id and
xref_code in ('SPS','BUS','ORG','OWN','FDN' ))
Upvotes: 6
Reputation: 310
with clause makes it easy, if with does not work , you can use alias in from clause
with b ( select sum(amt_tot) as bsum
from agbgift, aprxref, aprdclb where
aprxref_id = '1' and
agbgift_id = aprxref_xref_id and
aprxref_id = aprdclb_id and
xref_code in ('SPS','BUS','ORG','OWN','FDN' ))
, a (select sum(amt_tot) asum
from agbgift, aprdclb
where agbgift_id = '1' and agbgift_id = aprdclb_id )
select a.asum + b.bsum
from a, b
which is really in this case :
select a.asum + b.bsum
from (select sum(amt_tot) asum
from agbgift, aprdclb
where agbgift_id = '1' and agbgift_id = aprdclb_id) as a,
( select sum(amt_tot) as bsum
from agbgift, aprxref, aprdclb where
aprxref_id = '1' and
agbgift_id = aprxref_xref_id and
aprxref_id = aprdclb_id and
xref_code in ('SPS','BUS','ORG','OWN','FDN' )) as b
Upvotes: 0