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

从结果中获取第一个匹配项

  •  0
  • Madhu  · 技术社区  · 15 年前

    我有一个oracle sql查询

    select
        distinct 
        tab1.col1,
        tab2.col1
    from 
        table1 tab1 
        join table2 tab2 on tab1.col1 = tab2.col1
    

    在这里,我得到了不同值的预期结果。

    For Example : The result rows are
    
    1  2 
    3  4
    5  6
    

    select
        distinct 
        tab1.col1,
        tab2.col1,
        tab3.col1
    from 
        table1 tab1 
        join table2 tab2 on tab1.col1 = tab2.col1
        join table3 tab3 on tab1.col1 = tab3.col1
    

    这里的问题是表3返回了多个值。 这将导致基于表3的重复行。

    For Example : The result rows are
    1  2  4 
    1  2  5 
    3  4  1
    3  4  2
    5  6  3
    

    (如果您注意到第1行;2重复,3&4个(重复)

    我想做的是为了表3的连接,我想把 行的第一次出现。

    2 回复  |  直到 12 年前
        1
  •  4
  •   Baaju    15 年前

    这玩意儿对你有用!

    select 
        distinct  
        tab1.col1, 
        tab2.col1, 
        MIN(tab3.col1)
    from  
        table1 tab1  
        join table2 tab2 on tab1.col1 = tab2.col1 
        join table3 tab3 on tab1.col1 = tab3.col1 
    GROUP BY tab1.col1, tab2.col1
    

    编辑:思想,

    我假设第3列是一个不断增加的整数,在这种情况下这是可行的。您可以使用date列精确地定义聚合,以获得“行的第一次出现”。

        2
  •  1
  •   onof    15 年前
    select
        distinct 
        tab1.col1,
        tab2.col1,
        t3.col1
    from 
        table1 tab1 
        join table2 tab2 on tab1.col1 = tab2.col1
        join (select distinct col1 from table3) t3 on tab1.col1 = t3.col1