'How to calculate the sum in one table and then insert into another table?
I have two tables. The first table: order
|id |total|
|A001 | |
|A002 | |
The second table: goods
|id |price|order_id|
|B001 |100 |A001 |
|B002 |200 |A001 |
|B003 |300 |A002 |
Now how to write the SQL statement to calculate the SUM price in goods table which have the same order_id then insert into order table in total column, like this:
|id |total|
|A001 |300 |
|A002 |300 |
Solution 1:[1]
Update O
SET O.total = t.Sum_Of_Price
FROM Order AS O
INNER JOIN
(
Select order.id as ID, sum(goods.price) as Sum_Of_Price
from goods
INNER JOIN order
ON order.id = goods.order_id
group by order.id
) t
ON O.id = t.id
Solution 2:[2]
with temp(id, total) as (select order_id, sum(price) from goods group by order_id) update order o join temp t on o.id = t.id set o.total = t.total;
select * from order;
try it out here https://www.db-fiddle.com/f/caceQG8i4dWKZjUfhGRi2R/0
Solution 3:[3]
I find 'order' is a key word in sql, so I change the first table name to 'orders'.
update orders a
set total=
(
select sum(price)
from goods b
where a.id=b.order_id
)
where exists
(
select 1
from goods b
where a.id=b.order_id
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Teja Goud Kandula |
| Solution 2 | Rinkesh P |
| Solution 3 | ZHIMU ZHANG |
