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

后端 未结 3 1792
春和景丽
春和景丽 2020-12-21 22:22

I have Two tables in my access database

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

these tables are rela

相关标签:
3条回答
  • 2020-12-21 22:58

    Perform an update join by getting the SUM() first like

    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;
    
    0 讨论(0)
  • 2020-12-21 22:59

    When you say that it's linked by the productname field please tell me in table 1 that is a foreign key. 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.

    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;
    
    0 讨论(0)
  • 2020-12-21 23:03

    Because update queries in MS Access require updateable status, you cannot use a direct inner join on an aggregate query. Consider using the MS Access DSum() function:

    UPDATE table1
    SET table1.remainder = table1.quantity - 
        DSum("Sales", "table2", "ProductName='" & table1.ProductName & "'")
    
    0 讨论(0)
提交回复
热议问题