如何添加来自2个查询的值

时间:2009-06-10 06:23:45

标签: sql sql-server-2005 tsql

从1 st 查询我得到一些值,并且从2 nd 查询得到一些值。我想要两个值的总和。

查询1:

select sum(EAmount) from EstimateAmount where pid='3' group by pid

查询2:

select sum(OPEAmount) from OPEAmount where pid='3' group by pid

4 个答案:

答案 0 :(得分:13)

select 

(select sum(EAmount) from EstimateAmount 
where pid='3' 
group by pid) 
+ 
(select sum(OPEAmount) from OPEAmount 
where pid='3' 
group by pid) 

答案 1 :(得分:3)

Mitch解决方案是正确的,我只想在需要所有pid的总和并且可以扩展到更多聚合的情况下为这些情况添加更通用的解决方案:

with agg_EA as (
    select pid, sum(EAmount) as sumEA
    from EstimateAmount 
    group by pid) 
, agg_OPEA as (
    select pid, sum(OPEAmount) as sumOPE
    from OPEAmount 
    group by pid)
select sumEA+sumOPE
    from agg_EA
    join agg_OPEA on agg_EA.pid = agg_OPE.pid

答案 2 :(得分:0)

汇总和金额时,您还可以在嵌套表格中使用 Union All

select  sum(agg.Total) as GrandTotal
from    ( select sum(EAmount) as Total from EstimateAmount where pid='3' group by pid
      union all
      select sum(OPEAmount) as Total from OPEAmount where pid='3' group by pid
    ) agg

答案 3 :(得分:0)

加入他们:

SELECT sum(coalesce(e.EAmount,0) + coalesce(o.OPEAmount,0))
FROM EstimateAmount e
LEFT JOIN OPEAmount o ON o.pid = e.pid
WHERE e.pid = 3
GROUP BY e.pid