SQL查询,将值设置为自身加上另一个字段的值
我有一个客户表,其中SQL查询,将值设置为自身加上另一个字段的值,sql,oracle,select,sql-update,Sql,Oracle,Select,Sql Update,我有一个客户表,其中customerid作为PK和currentordertotal字段。我想合并两个客户记录的currentordertotal 例如: Customer C1, Current Order Total = 2 Customer C2, Current Order Total = 4 我想将C1的当前订单总额更新为自身(2)加上C2的当前订单总额(so 6) 比如: UPDATE customers SET currentordertotal = (itself + cur
customerid
作为PK
和currentordertotal
字段。我想合并两个客户记录的currentordertotal
例如:
Customer C1, Current Order Total = 2
Customer C2, Current Order Total = 4
我想将C1的当前订单总额
更新为自身(2)加上C2的当前订单总额
(so 6)
比如:
UPDATE customers SET currentordertotal = (itself + currentordertotal WHERE customerid = C2) WHERE customerid = C1;
我在网上搜索过类似的查询,但找不到
这是一个Oracle数据库您可以执行子查询
UPDATE customers SET currentordertotal = currentordertotal + (select currentordertotal from customers WHERE customerid = C2) WHERE customerid = C1
您可以执行子查询
UPDATE customers SET currentordertotal = currentordertotal + (select currentordertotal from customers WHERE customerid = C2) WHERE customerid = C1
子查询是正确的方法,但我们要小心:
update customers
set currentordertotal = (coalesce(currentordertotal, 0) +
coalesce((select c2.currentordertotal
from customers c2
where c2.customerid = 'C2'
), 0)
)
where customerid = 'C1';
合并是为了防止第二个客户丢失或值为
NULL
子查询是正确的方法,但我们要小心:
update customers
set currentordertotal = (coalesce(currentordertotal, 0) +
coalesce((select c2.currentordertotal
from customers c2
where c2.customerid = 'C2'
), 0)
)
where customerid = 'C1';
合并是为了防止第二个客户丢失或值为NULL