SQL查询为自己设置一个值加上另一个字段的值

时间:2016-12-08 16:01:14

标签: sql select sql-update oracledb

我有一个客户表,customeridPKcurrentordertotal字段。我想将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 DB

2 个答案:

答案 0 :(得分:2)

你可以做一个子查询

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

答案 1 :(得分:2)

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

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

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