【问题标题】:SQL Query to Set a Value to Itself Plus Value of Another FieldSQL 查询将值设置为自身加上另一个字段的值
【发布时间】:2017-04-23 22:40:12
【问题描述】:

我有一张客户表,customerid 作为PK 和一个currentordertotal 字段。我想将currentordertotal 合并为两个客户记录。

例如:

Customer C1, Current Order Total = 2

Customer C2, Current Order Total = 4

我想将 C1’s Current Order Total 更新为它自己 (2) 加上 C2’s Current Order Total (所以 6)。

比如:

UPDATE customers SET currentordertotal = (itself + currentordertotal  WHERE customerid = C2) WHERE customerid = C1;

我在网上搜索过类似的查询,但找不到。

这是一个 Oracle 数据库

【问题讨论】:

    标签: sql oracle select sql-update


    【解决方案1】:

    子查询是正确的方法,但我们要小心:

    update customers
        set currentordertotal = (coalesce(currentordertotal, 0) +
                                 coalesce((select c2.currentordertotal
                                           from customers c2
                                           where c2.customerid = 'C2'
                                          ), 0)
                                )
        where customerid = 'C1';
    

    如果第二个客户丢失或值为NULL,则合并。

    【讨论】:

      【解决方案2】:

      你可以做一个子查询

      UPDATE customers SET currentordertotal = currentordertotal  + (select currentordertotal from customers WHERE customerid = C2) WHERE customerid = C1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-01-25
        • 1970-01-01
        • 2014-10-19
        • 2017-05-07
        • 2018-02-07
        • 1970-01-01
        • 1970-01-01
        • 2017-12-25
        相关资源
        最近更新 更多