简体   繁体   English

SQL,如何对两个不同查询的两个和求和

[英]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子句很容易,如果with不能正常工作,则可以在from子句中使用别名

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  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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