[英]How to update ms access database table using update and sum() function?
I have Two tables in my access database我的访问数据库中有两个表
these tables are related together using "product name",How can I update"reminder" from table1 with the value of "quantity form first table - Sum(sales) from second table"这些表使用“产品名称”关联在一起,如何使用“第一个表中的数量形式 - 第二个表中的总和(销售额)”的值更新表 1 中的“提醒”
Because update queries in MS Access require updateable status, you cannot use a direct inner join on an aggregate query.因为 MS Access 中的更新查询需要可更新状态,所以您不能对聚合查询使用直接内部联接。 Consider using the MS Access DSum() function:考虑使用 MS Access DSum()函数:
UPDATE table1
SET table1.remainder = table1.quantity -
DSum("Sales", "table2", "ProductName='" & table1.ProductName & "'")
Perform an update join by getting the SUM()
first like通过首先获取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;
When you say that it's linked by the productname field please tell me in table 1 that is a foreign key.当您说它由 productname 字段链接时,请告诉我表 1 中的外键。 Since you already have an ID in table 2 there's no reason not to use that ID as the foreign key in table 1.由于表 2 中已有 ID,因此没有理由不将该 ID 用作表 1 中的外键。
If you were to do that the update would be as simple as this:如果您要这样做,更新将像这样简单:
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.