簡體   English   中英

如何使用 update 和 sum() 函數更新 ms access 數據庫表?

[英]How to update ms access database table using update and sum() function?

我的訪問數據庫中有兩個表

  • table1(ID,productname,quantity,remainder)
  • table2(ID,productname,sales)

這些表使用“產品名稱”關聯在一起,如何使用“第一個表中的數量形式 - 第二個表中的總和(銷售額)”的值更新表 1 中的“提醒”

因為 MS Access 中的更新查詢需要可更新狀態,所以您不能對聚合查詢使用直接內部聯接。 考慮使用 MS Access DSum()函數:

UPDATE table1
SET table1.remainder = table1.quantity - 
    DSum("Sales", "table2", "ProductName='" & table1.ProductName & "'")

通過首先獲取SUM()來執行更新連接

UPDATE a 
SET    a.remainder = x.SaleTotal
FROM   table1 a 
       INNER JOIN (SELECT productname, SUM(sales) AS SaleTotal 
                   FROM TABLE2 GROUP BY productname) x 
       ON a.productname = x.productname;

當您說它由 productname 字段鏈接時,請告訴我表 1 中的外鍵。 由於表 2 中已有 ID,因此沒有理由不將該 ID 用作表 1 中的外鍵。

如果您要這樣做,更新將像這樣簡單:

update table1 
set table1.quantity = table1.quantity - SUM( table2.sales ) 
from table1
inner join table2 on table1.productID = table2.productID
where table1.productID = 1;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM