Search code examples
sqldatabasesap-iq

query to Sum product of two tables


I have a 2 tables with names and balances ex

Table A

  Name    | Amount
-----------------------                           
  Abraham | 500  
  Abraham | 100  
  George  | -200  
  George  | 200  
  Thomas  | 300  
  Thomas  | -100

Table B

  Name    | Amount
-------------------------                           
  Abraham | 100  
  Abraham | 200  
  George  | -200  
  George  | 50  
  Thomas  | 400  
  Thomas  | 300   
  Albert  | -100       
  Albert  | -200 

So I need to add the 2 tables up , every name has a positive and a negative, I dont know if Table A and table B will have the same amount of unique names or not so it could be either or. When I run the query

Select sum(Amount)  
from table_A  
group by Name  

This query Works for either Table A or Table B individually but when I try to run a query like this I get an outrageous number

Select a.Name , sum(a.amount) + sum(b.amount)
from table_A full outer join table_B b on a.Name = b.Name
group by a.Name

is there a way to do this in one query ?


Solution

  • My query works fine using UNION ALL. See my query and SQL Fiddle Demo below:

    SELECT Name,SUM(Amount)Amount FROM(
    SELECT Name, Amount
        FROM TableA
    UNION ALL
    SELECT Name, Amount
        FROM TableB) AS A GROUP BY Name
    

    SQL FIDDLE DEMO HERE