从一张表中扣除销售金额并将总金额更新为另一张表

时间:2015-05-29 16:18:52

标签: sql-server sql-server-2008-r2 sql-update sql-server-ce

使用SQL Server Compact Edition(2008 R2)

  1. 表格(CustomerOrders
  2. PK(客户:SID,订单:Customer_SID
  3. 我想对Orders.Sales_Amount求和,并根据Customer.Sales_Total将总数写为SID

    我必须错误地使用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 个答案:

答案 0 :(得分:1)

有一种更简单的方法来完成您所追求的更新:

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

Demo here