代码之家  ›  专栏  ›  技术社区  ›  dbwhite64

Oracle SQL-左联接导致重复

  •  0
  • dbwhite64  · 技术社区  · 7 年前

    祝大家星期五快乐!

    我有三张正在使用的表,我在连接方面遇到了困难。表1包含字段name、id、state和sales。表2包含state和stateID(除其他外)。表3包含stateID和region(除其他外)。我需要的是表1中的stateID和region字段。

    我尝试的是

    select name, id, state, stateID, region, sales
    from table 1 taba
    left join table 2 tabb
    on taba.state = tabb.state
    left join table 3 tabc
    on tabb.stateid = tabc.stateid
    

    这使表1从约16k行增加到约100k行

    我只尝试了自己的第一次联接,得到了正确的行数。当我进行第三次连接时,如何消除这些重复行?

    Table 1 
    Name   ID    State        Sales  
    John   01    Texas       50,234  
    Steve  02    Washington  39,261
    Amanda 03    Ohio        67,892
    
    Table 2 
    State       StateID
    Texas       TX
    Washington  WA 
    Ohio        OH
    
    Table 3
    StateID    Region
    TX         South
    WA         Northwest
    OH         Midwest
    

    我需要它看起来像这样:

    Name   ID    State        StateID   Region   Sales  
    John   01    Texas        TX       South     50,234  
    Steve  02    Washington   WA       Northwest 39,261
    Amanda 03    Ohio         OH       Midwest   67,892
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   dfundako    7 年前

    我假设每个州都有多个地区,但表1中没有任何地区。因此,当您连接到表3时,该状态中有100个区域,并且您唯一要连接的是一个stateID,它将返回所有100个区域。

    您可能需要在第一个表中使用region来指示区域和销售发生的状态,或者可以在查询中抛出DISTINCT。

    select DISTINCT name, id, state, stateID, region, sales
    from table 1 taba
    left join table 2 tabb
    on taba.state = tabb.state
    left join table 3 tabc
    on tabb.stateid = tabc.stateid
    

    根据新提供的表和数据,这将为您提供所需的:

    select name, id, state, stateID, region, SUM(sales) AS sales
        from table1 taba
        left join table2 tabb
        on taba.state = tabb.state
        left join table3 tabc
        on tabb.stateid = tabc.stateid
    GROUP BY name, id, state, stateID, region
    
        2
  •  0
  •   gui.co    7 年前

    我认为使用这个查询应该可以完成这项工作。

    select name, id, state, stateID, region, sales
    from table1 natural join table2 natural join table3
    

    因为您的表使用相同的属性名称,所以可以使用自然连接(它将只保留公共属性,假设表1中的所有状态都在表2中,而表2中的所有stateID都在表3中)。

    如果您需要每个名称的销售额总和(您的问题中不清楚):

    select name, id, state, stateID, region, SUM(sales)
    from table1 natural join table2 natural join table3
    group by name, id, state, stateID, region