繁体   English   中英

根据Oracle SQL中其他多个行的值更新行

[英]Update row based on value of multiple other rows in Oracle SQL

我想查找彼此相似的行,如果一行具有任何相似的行,请更新一个字段。 我的桌子看起来像这样:

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的“相似”字段从默认值(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

这是一种可以在包括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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM