简体   繁体   中英

SQL, how to sum two sums from two different queries

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'

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' ))

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  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM