2015-05-29 93 views
0

使用SQL Server精簡版(2008 R2)總銷售金額和總更新到另一個表

  1. 表(CustomerOrders
  2. PK(客戶:SID,訂單:Customer_SID

我要總結的Orders.Sales_Amount和寫入基礎上,SID S中的總數變爲Customer.Sales_Total

我必須錯誤地使用inner join語句,因爲我在FROM語句中出現錯誤。

UPDATE customer 
SET sales_total = aggr.sales_total 
FROM customer 
INNER JOIN (
    SELECT sid 
     ,sum(sales_amount) sales_total 
    FROM customer 
    INNER JOIN orders 
     ON (customer.sid = orders.customer_Sid) 
    GROUP BY customer.sid 
    ) aggr 
    ON customer.sid = aggr.sid; 

回答

1

沒有完成更新的更簡單的方法你是後:

UPDATE customer 
SET sales_total = (SELECT SUM(sales_amount) 
        FROM orders 
        WHERE orders.customer_Sid = customer.sid) 

Demo here