簡體   English   中英

SQL,如何對兩個不同查詢的兩個和求和

[英]SQL, how to sum two sums from two different queries

我試圖在兩個不同的條件下獲取相同變量的總和。 只是想知道是否有辦法將它們加在一起。 查詢的細節並不是很相關。 基本上只是嘗試將第一個和與第二個和相加。

例如 -

首先查詢:

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

我正在尋找的最終結果是“第一查詢總和” +“第二查詢總和”

在這種情況下,就這么簡單:

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子句很容易,如果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  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM