2015-09-04 79 views
1

我想加入3個表,以得到如下結果:加入多個字段3個表

 Table_A: 
    Customer Product  Div_Num  Importance 
    C1   P1   X   .5 

 
    Table_B: 
    Div_Num   Div_Name 
    X    Arizona 

 
    **Table_C:** 
    *Customer Product  Sales* 
    C1  P1  15 
    C1  P1  20 
 **Desired Results:** 
    *Customer Product  Div_Name Importance Sum(Sales)* 
    C1   P1   Arizona  .5   35 
Select Table_A.Customer, Table_A.Product, Table_B.Div_Name, Table_A.Importance, sum(Table_C.Sales) 
    From Table_A 
     Inner Join Table_B 
     On Table_A.Div_Num = Table_B.Div_Num 
     Inner Join Table_C 
     On Table_A.Customer = Table_C.Customer And Table_A.Product = Table_C.Product 
    Where Table_A.Product IN ('P1', 'P2', 'P3') 

我得到錯誤42S02(29):關係不存在

+1

嘗試簡化您的查詢,並逐步增加了複雜性,直到你遇到錯誤,所以你可以看到是什麼原因造成的。例如,從SELECT * FROM Table_A開始WHERE Table_A.Product IN(P1,P2,P3)。如果可行,請將聯接添加到Table_B,依此類推。 –

+0

我應該提到當我使用總和項添加第二個連接時出現錯誤。其他的一切工作正常之前,我把它放在 – Adam12344

回答

0

SQL FIDDLE DEMO

你忘了GROUP BY

Select Table_A.Customer, Table_A.Product, Table_B.Div_Name, Table_A.Importance, sum(Table_C.Sales) 
From Table_A 
    Inner Join Table_B 
    On Table_A.Div_Num = Table_B.Div_Num 
    Inner Join Table_C 
    On Table_A.Customer = Table_C.Customer And Table_A.Product = Table_C.Product 
Where Table_A.Product IN ('P1', 'P2', 'P3') 
GROUP BY Table_A.Customer, Table_A.Product, Table_B.Div_Name, Table_A.Importance 
+0

我的錯誤,原代碼中有單引號(我編輯它)。該錯誤實際上是在我添加第二個加入 – Adam12344

+0

完成後進入的。檢查更新。 –

+0

你好亞當。這是否解決了你的問題? –

0

我建議總和是一組由項。除非你有一個小組來創建你將要總結的捲起,否則你不能擁有它。你可能需要:

group by Table_A.Customer, Table_A.Product, Table_B.Div_Name, Table_A.Importance