来自两个不同表的SQL SUM

时间:2012-12-10 13:23:43

标签: sql sql-server-2008

我正在尝试构建一个SQL Sum语句来对来自不同表的数据求和。每个表都有一个共同的SalesRep字段。我在确定如何正确构造SQL时遇到了一些麻烦。

我知道下面的语法是错误的并且不起作用,但我只是不是SQL专家。我确信这很简单。有人能帮帮我吗?

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 个答案:

答案 0 :(得分:1)

表之间没有关系,对吧?

可能比这样吗?

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

问候

答案 1 :(得分:0)

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;

答案 2 :(得分:0)

我添加了IsNull,因为如果其中一列为null,您将在答案中得到null并且您不希望这样。

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

这适合我。