SQL SUM from two different tables

2019-08-18 23:46发布

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;

3条回答
聊天终结者
2楼-- · 2019-08-19 00:08

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

查看更多
趁早两清
3楼-- · 2019-08-19 00:20

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.

查看更多
放荡不羁爱自由
4楼-- · 2019-08-19 00:31
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;
查看更多
登录 后发表回答