繁体   English   中英

来自同一个表的 SUM 的 SQL 更新值

[英]SQL update value with SUM from same table

我有桌头。 有 ep、order_number、ont 列。 我需要每个记录集都作为 SUM ep 并具有相同的 order_number 值。

我尝试过这个:

UPDATE leads as l1 SET ont = (SELECT SUM(ep) FROM leads as l2  WHERE l2.order_number= l1.order_number);

有错误:表 'l1' 被指定两次,既作为 'UPDATE' 的目标,也作为单独的数据源

我该如何解决这个问题? 谢谢!

使用多表更新版本

drop table if exists t;
create table t(ont int,op int,order_number int);
insert into t values (1,10,1),(1,2,1);

update t 
join (select order_number,sum(op) sumop from t group by order_number) t1 on t1.order_number = t.order_number
set ont = sumop;

select * from t;

+------+------+--------------+
| ont  | op   | order_number |
+------+------+--------------+
|   12 |   10 |            1 |
|   12 |    2 |            1 |
+------+------+--------------+
2 rows in set (0.00 sec)

暂无
暂无

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

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