简体   繁体   中英

SQL update value with SUM from same table

I have table leads. There are columns ep, order_number, ont. I need for each record set ont as SUM ep with same order_number value.

I tried it:

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

Have error : Table 'l1' is specified twice, both as a target for 'UPDATE' and as a separate source for data

How can I solve this issue? Thanks!

Use multi table update version

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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