简体   繁体   中英

Get a sum from one table and update a column in another using SQL server

table 1 = customer | primary-key = customer.sid
table 2 = orders   | foreign-key = orders.customer_sid

I would like to sum orders.sale_amount where customer.sid = orders.customer_sid and update customer.sales_total .

I am new to SQl and here was my original statement (which doesn't work)

 UPDATE customer
 inner JOIN orders ON (customer.sid = orders.customer_Sid)
 SET customer.sales_total = SUM(orders.sale_amount)
 GROUP BY customer.sid;
Update customer
Set Total=Od.Tot
From customer C 
    cross apply (Select SUM (O.sale_amount) Tot 
                From Orders O Where O.customer_Sid=C.sid) Od

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