【问题标题】:SQL, how to sum two sums from two different queriesSQL,如何将两个不同查询的两个总和相加
【发布时间】:2014-09-27 15:53:47
【问题描述】:

我试图在两种不同的条件下获取同一变量的总和。只是想知道是否有办法将这些添加在一起。查询的细节并不太相关。基本上只是尝试将第一个总和与第二个总和相加。

例如--

第一个查询:

  select sum(amt_tot)
  from agbgift, aprdclb
  where agbgift_id = '1' and agbgift_id = aprdclb_id  

第二次查询:

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

我正在寻找的最终结果是'First Query Sum' + 'Second Query Sum'

【问题讨论】:

标签: mysql sql sum


【解决方案1】:

在这种情况下,就这么简单:

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

【讨论】:

  • 更简单的形式:SELECT (SELECT SUM(something) FROM table1 WHERE a = 1) + (SELECT SUM(something) FROM table2 WHERE a = 1) AS total
  • 谢谢,但是怎么这么简单呢?完全一样。
【解决方案2】:

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  

在这种情况下确实如此:

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  

【讨论】:

  • 谢谢,第一部分非常有用。好像得到了一些结果,只需要用数据库信息分析一下是否正确! :)
猜你喜欢
  • 2018-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-18
  • 1970-01-01
  • 1970-01-01
  • 2017-05-18
  • 1970-01-01
相关资源
最近更新 更多