通过连接表从不同的表中获取两个总和

时间:2016-05-23 10:24:36

标签: sql sql-server

我试图输出以下内容:

ValueSum1 | ValueSum2
8 | 10

但是我有点困难。我有的表是:

表1

ID  Value1  JoiningValue
1   3   1
2   2   2
3   3   2

表2

ID  Value1  JoiningValue
1   5   3
2   2   3
3   2   3
4   1   2

JoinTable

ID
1
2
3
4
5

我需要能够将JoinTable加入查询,因为我需要能够针对JoinTable中的值设置where条件。 我目前有:

SELECT SUM(Table1.Value1) 'ValueSum1',SUM(Table2.Value1) 'ValueSum2' From JoinTable
Left Join Table1
On JoinTable.ID = Table1.Joiningvalue
Left Join Table2
On JoinTable.ID = Table2.JoiningValue

然而,这给了我输出:

ValueSum1   ValueSum2
8   11

2 个答案:

答案 0 :(得分:3)

在加入之前汇总值

SELECT t1.ValueSum1, t2.ValueSum2
FROM JoinTable jt Left Join
     (SELECT Joiningvalue, SUM(Table1.Value1) as ValueSum1
      FROM Table1
      GROUP BY Joiningvalue
     ) t1
     On jt.ID = t1.Joiningvalue LEFT JOIN
     (SELECT Joiningvalue, SUM(Table2.Value1) as ValueSum2
      FROM Table2
      GROUP BY Joiningvalue
     ) t2
     On jt.ID = t2.JoiningValue;

答案 1 :(得分:0)

CREATE TABLE #Table1(ID  INT,
                    Value1  INT,
                    JoiningValue INT)
INSERT INTO #Table1 VALUES
(1,3,1)
,(2,2,2)
,(3,3,2)

CREATE TABLE #Table2(ID INT,
                    value1 INT,
                    JoiningValue INT)

INSERT INTO #Table2 VALUES
(1,5,3)
,(2,2,3)
,(3,2,3)
,(4,1,2)


CREATE TABLE #Join(ID INT)
INSERT INTO #Join VALUES
(1)
,(2)
,(3)
,(4)
,(5)



SELECT  SUM(T1.Value1) ValueSum1,
        SUM(T2.value1) ValueSum2
FROM 
#Join J
INNER JOIN #Table1 T1
    ON J.ID = T1.ID
RIGHT JOIN #Table2 T2
    ON J.ID = T2.ID