【问题标题】:Update row based on value of multiple other rows in Oracle SQL根据 Oracle SQL 中多个其他行的值更新行
【发布时间】:2014-05-03 12:23:08
【问题描述】:

我想找到彼此相似的行,如果一行有任何相似的行,则更新一个字段。我的桌子是这样的:

OrderID  |  Price  | Minimum Number | Maximum Number | Volume | Similar 
1         45        2                 10                250        0  
2         46        2                 10                250        0   
3         60        2                 10                250        0

此上下文中的“相似”表示具有相同最大数量、最小数量和体积的行。价格可以不同,但​​最多相差2。

在此示例中,OrderID 为 1 和 2 的订单相似,但 3 没有相似的行(因为即使它具有相同的最小数量、最大数量和交易量,但其价格不在订单 1 的 2 个单位之内和 2)。

然后,我想将订单 1 和 2 的归档“Similar”从默认值 (0) 更新为 1。因此,上述示例的输出将是:

OrderID  |  Price  | Minimum Number | Maximum Number | Volume | Similar 
1         45        2                 10                250        1
2         46        2                 10                250        1
3         60        2                 10                250        0

【问题讨论】:

    标签: sql oracle sql-update row


    【解决方案1】:

    这是一种适用于大多数数据库(包括 Oracle)的 ANSI 标准 SQL 方法。它实现了您使用相关子查询设定的逻辑:

    update table t
        set similar = 1
        where exists (select 1
                      from table t2
                      where t2.minimum = t.minimum and
                            t2.maximum = t.maximum and
                            t2.volume = t.volume and
                            abs(t2.price - t.price) <= 2 and
                            t2.OrderId <> t.OrderId
                     );
    

    编辑:

    在我看来,“相似”字段可能是相似字段中的最小值 OrderId。您可以将上述想法扩展为:

    update table t
        set similar = (select min(orderId)
                       from table t2
                       where t2.minimum = t.minimum and
                             t2.maximum = t.maximum and
                             t2.volume = t.volume and
                             abs(t2.price - t.price) <= 2 and
                             t2.OrderId <> t.OrderId
                      )
        where exists (select 1
                      from table t2
                      where t2.minimum = t.minimum and
                            t2.maximum = t.maximum and
                            t2.volume = t.volume and
                            abs(t2.price - t.price) <= 2 and
                            t2.OrderId <> t.OrderId
                     );
    

    如果是这种情况,默认值应该是NULL 而不是0

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-21
      • 1970-01-01
      • 2022-08-16
      • 1970-01-01
      • 2021-07-16
      • 2020-08-12
      相关资源
      最近更新 更多