【问题标题】:Sum sale amount from one table and update the total to another table汇总一张表的销售额并将总额更新到另一张表
【发布时间】:2015-05-29 16:18:52
【问题描述】:

使用 SQL Server Compact Edition (2008 R2)

  1. 表格(CustomerOrders
  2. PK(客户:SID,订单:Customer_SID

我想对Orders.Sales_Amount 求和,然后根据SIDs 将总数写入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;

【问题讨论】:

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


    【解决方案1】:

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

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

    Demo here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-24
      • 1970-01-01
      • 1970-01-01
      • 2022-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-05
      相关资源
      最近更新 更多