如何使用where和sum语句加入两个表

时间:2015-04-30 03:47:41

标签: sql

亲爱的我只有两张桌子

表1

RecdId  RecdNo  
1   A/1 
2   A/2 
3   A/3 

表2

RecdId  RecdAmt1    RecdAmt2    RecdAmt3
1   100 10  5
1   150 20  10
1   200 30  15
2   500 5   50
2   400 10  60
3   100     5

我想要解决方案,如何使用Table1.RecdId = Tabble2.RecdId

的总和加入上面的两个表

结果我需要

RecdId  RecdNo  TotRecdAmt1 TotRecdAmt2 TotRecdAmt3
1   A/1 450 60  30
2   A/2 900 15  110
3   A/3 100     5

感谢你,

3 个答案:

答案 0 :(得分:1)

您可以inner join两个表并使用group by子句为sumRecdId的每个组合计算RecdNo

select t1.RecdId
     , t1.RecdNo
     , sum(t2.RecdAmt1) as TotRecdAmt1
     , sum(t2.RecdAmt2) as TotRecdAmt2
     , sum(t2.RecdAmt3) as TotRecdAmt3
from tbl1 t1 
join tbl2 t2 on t1.RecdId = t2.RecdId
group by t1.RecdId
       , t1.RecdNo

SQLFiddle

答案 1 :(得分:0)

SELECT T1.RECDID, T1.RECDNO, TotRecdAmt1, TotRecdAmt2, TotRecdAmt3 
FROM TABLE1 T1, (SELECT RECdID, SUM(RecdAmt1) TotRecdAmt1, SUM(RecdAmt2) TotRecdAmt2, 
                   SUM(RecdAmt3) TotRecdAmt3 FROM TABLE2 GROUP BY RECdID) T2 
WHERE T1.RECdID = T2.RECDID;

答案 2 :(得分:0)

SELECT Table1.RecdId,RecdNo,SUM(RecdAmt1) AS TotRecdAmt1,
SUM(RecdAmt2) AS TotRecdAmt2,
SUM(RecdAmt3) AS TotRecdAmt3
FROM Table1,Table2
WHERE Table1.RecdId=Table2.RecdId
GROUP BY Table1.RecdId,RecdNo