【问题标题】:Oracle Remove Duplicate Combination of Threeoracle去除重复的三个组合
【发布时间】:2020-10-13 19:17:49
【问题描述】:

我有一个返回 3 列和 3 个哈希值的视图。 第三列有时为空。

这些组合以不同的顺序重复,例如:

1,2,3
1,3,2
2,1,3
2,3,1
3,1,2
3,2,1

我认为每 3 个连接的哈希有 6 行。

这些哈希实际上是同一个文件的 ID(但现在不相关)。

**

我尝试了各种方法,似乎找到了合适的解决方案 - 但我想知道是否有更好的方法。 另请注意,有时可能缺少 6 行之一。

我目前正在尝试以下方法,它似乎正在工作:

select one, two, three from DUPLICATE_DOCUMENTS_3JOINS
where (three is null and two<one) or (three<two AND two<one);

有什么想法吗?

【问题讨论】:

    标签: sql oracle select duplicates sql-order-by


    【解决方案1】:

    如果您只想要一行,那么想到的最简单的选项是行限制查询:

    select d.*
    from duplicate_documents_3joins d
    order by one, two, three
    fetch first row only
    

    在 Oracle 11g 及更早版本中,您可以改用row_number():

    select one, two, three
    from (
        select d.*, row_number() over(order by one, two, three) rn
        from duplicate_documents_3joins d
    ) d
    where rn = 1
    

    【讨论】:

    • 抱怨 SQL 命令没有正确结束。可能是小事。
    • 您运行的是哪个版本的 Oracle? fetch 语法是在 12c 中添加的。
    • 开枪,11 样东西。不过没关系,答案与其他人有关。
    • @Menios:我用早期版本的等效解决方案更新了我的答案。
    【解决方案2】:

    您可以使用不同的选择:

    SELECT DISTINCT
        LEAST(one, two, three) AS one,
        CASE WHEN one > two AND one < three
             THEN one
             WHEN LEAST(one, two, three) = one AND two < three
             THEN two
             ELSE three END AS two,
        GREATEST(one, two, three) AS three
    FROM yourTable;
    

    鉴于示例数据集中的六条记录,即 1、2 和 3 的六个排列,上述查询将只返回一条记录 1、2、3。上述逻辑适用于任何一组一、二、三个值(顺序不限)。

    【讨论】:

      【解决方案3】:

      如果您有三个连接,请在连接中解决问题:

      select . . .
      from t t1 join
           t t2
           on . . . and t1.one < t2.two join
           t t3
           on . . . and t2.two < t3.three
      

      如果你必须处理left joins 可能会稍微复杂一点,但想法会类似。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-16
        • 1970-01-01
        • 1970-01-01
        • 2016-07-18
        • 2023-01-23
        • 2010-12-24
        • 2021-06-23
        • 1970-01-01
        相关资源
        最近更新 更多