【问题标题】:Joining without duplicate records/result sets在没有重复记录/结果集的情况下加入
【发布时间】:2019-01-08 01:34:57
【问题描述】:

我正试图弄清楚如何连接两个表,其中一个表具有基本上重复的行,但只返回一个结果集。基本上 tableOne 有项目和类别,而 tableTwo 是唯一有项目颜色的地方,但是该表中的一些记录有多行用于位置。那里真的没有区别,它只是用于遗留数据的目的。

我只需要项目的颜色,它在 tableTwo 中总是相同的,但是由于表 2 中有 4 条记录,我下面的查询总是返回 4 条记录,我只想要一个

tableOne

item | category
---------------
 1        A

表二

item  |  category  |  color  |  location
-----------------------------------------
 1         A           Red        1
 1         A           Red        2
 1         A           Red        3
 1         A           Red        4

查询:

select t1.item,t2.category,t2.color
from tableOne t1
left join tableTwo t2 
    on t1.item = t2.item 
    and t1.category = t2.category

我怎样才能运行它以基本上忽略位置并且只返回一条记录用于 DB2 中的查询?

【问题讨论】:

    标签: sql db2


    【解决方案1】:

    一种方法使用row_number()

    select t1.item, t1.category, t2.color
    from tableOne t1 left join
         (select t2.*,
                 row_number() over (partition by item, category order by item) as seqnum
          from tableTwo t2 
         ) t2
         on t2.item = t1.item and
            t2.category = t1.category and
            t2.seqnum = 1;
    

    我认为您应该从t1 中获取category 而不是t2,除非您在没有匹配项时明确需要NULL 值。

    【讨论】:

    • @TomN。 . . .它应该。 DB2 长期支持row_number()
    【解决方案2】:

    使用SELECT DISTINCT

    select distinct t1.item,t2.category,t2.color 
    from tableOne t1
    left join tableTwo t2 on t1.item = t2.item and t1.category = t2.category
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-02
      • 1970-01-01
      • 2013-04-05
      • 1970-01-01
      • 2021-11-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多