SQL SUM from two different tables

2019-08-19 00:06发布

问题:

I'm trying to build a SQL Sum statement to sum data from different tables. Each table has a SalesRep field in common. I'm having a bit of trouble figuring out how to to construct the SQL correctly.

I know the below syntax is wrong and won't work but I'm just not a SQL expert. I'm sure it's something simple. Can someone help me please?

SELECT SalesRepID, SUM(SELECT SalesRepID, Sum(tblClientAdditions.Amount) AS Subtotal
FROM tblClientAdditions GROUP BY SalesRepID + SELECT SalesRepID, 
Sum(tblAccounts.ReceivedAmount) AS Subtotal1
FROM tblAccounts GROUP BY SalesRepID) FROM tblSalesReps;

回答1:

There is no relation between the tables, right?

Than maybe something like this?

SELECT (SELECT SUM(value) FROM table1) + (SELECT SUM(value) FROM table2) as result

Greetings



回答2:

SELECT SalesRepID, 

(SELECT Sum(tblClientAdditions.Amount) FROM tblClientAdditions 
where tblClientAdditions.SalesRepID =tblSalesReps.SalesRepID)
+
(SELECT Sum(tblAccounts.ReceivedAmount) FROM tblAccounts
where tblAccounts.SalesRepID =tblSalesReps.SalesRepID)

FROM tblSalesReps;


回答3:

I added IsNull because if one of the columns are null you will get null in the answer and you don't want that.

SELECT ISNull(SUM(Table1.column1),0)+ (SELECT ISNull(SUM(Table2.column1),0) FROM Table2) FROM Table1 

This works for me.