SQL Query to sum fields from different tables

前端 未结 5 1320
無奈伤痛
無奈伤痛 2020-12-30 15:57

I\'m a humble programmer that hates SQL ... :) Please help me with this query.

I have 4 tables, for example:

Table A:
Id Total
1  100
2  200
3  500

         


        
相关标签:
5条回答
  • 2020-12-30 16:07

    This might help other users.

    SELECT Total=(Select Sum(Amount) from table a)+(Select Sum(Amount) from table b)+(Select Sum(Amount) from table c)
    
    0 讨论(0)
  • 2020-12-30 16:10

    Try this code SELECT Total=isnull((Select Sum(Isnull(Amount,0)) from table a),0)+isnull((Select Sum(isnull(Amount,0)) from table b),0)+isnull((Select Sum(isnull(Amount,0)) from table c),0)

    0 讨论(0)
  • 2020-12-30 16:22

    Or you can take advantage of using SubQueries:

    select A.ID, A.Total, b.SB as AmountB, c.SC as AmountC, d.SD as AmountD
    from A
      inner join (select ExtID, sum(Amount) as SB from B group by ExtID) b on A.ID = b.ExtID
      inner join (select ExtID, sum(Amount) as SC from C group by ExtID) c on c.ExtID = A.ID
      inner join (select ExtID, sum(Amount) as SD from D group by ExtID) d on d.ExtID = A.ID
    
    0 讨论(0)
  • 2020-12-30 16:26

    From your description, this query should give you an error as you are using the non-existent column dbo.A.Amount in your group by. Changing this to dbo.A.Total might be what you need.

    If you need all the amounts together, then try this query:

    select A.Id, A.Total, sum(B.Amount + C.Amount + D.Amount) AS Total_Amount
    from A
      inner join B on A.Id = B.ExtId
      inner join C on A.Id = C.ExtId
      inner join D on A.Id = D.ExtId
    group by A.Id, A.Total;
    
    0 讨论(0)
  • 2020-12-30 16:32

    This one also works well

    SELECT (SELECT SUM(Amount) FROM TableA) AS AmountA, (SELECT SUM(Amount) FROM TableB) AS AmountB, (SELECT SUM(Amount) FROM TableC) AS AmountC, (SELECT SUM(Amount) FROM TableD) AS AmountD

    0 讨论(0)
提交回复
热议问题