2016-05-23 300 views
1

我試圖輸出如下:獲取來自不同表的兩個和一個連接表

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 

我需要ŧ o能夠將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 

回答

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; 
+0

謝謝,這是偉大的 - 做了我想要的東西。唯一需要改變的是:SELECT SUM(t1.ValueSum1),SUM(t2.ValueSum2)以獲得我需要的確切輸出。 – Revokez

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 
相關問題