在多个字段上连接3个表

时间:2015-09-04 21:31:50

标签: sql join

我正在尝试加入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):关系不存在

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我建议总和按术语分组。你不能拥有它,除非你有一个小组来创建你要总结的汇总。你可能需要:

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