简体   繁体   English

通过计算另一个表中的值来更新和设置列行值

[英]UPDATE and SET column row values by calculating values from antoher table

I have two tables:我有两个表:

products - which has UnitsSold(total/cumulative amount of sold products/item), and产品 - 具有 UnitsSold(已售产品/项目的总/累计数量),以及

sales - which has SoldQuantity (how many units sold per transaction) sales - 有 SoldQuantity(每笔交易售出多少单位)

The same unit could be sold many times, so we need to calculate how many times it sold from sales table which have SoldQuantity and show the result in UnitsSold, which will show how many items we sold in total per item.同一个单位可以多次销售,因此我们需要从具有 SoldQuantity 的销售表中计算它的销售次数,并在 UnitsSold 中显示结果,这将显示我们每件商品总共销售了多少件商品。

I use this Query but it return some problems我使用这个查询,但它返回一些问题

#1111 - Invalid use of group function): #1111 - 无效使用组功能):

UPDATE products 
 JOIN sales 
   ON sales.Itemcode = products.Code 
  SET products.UnitsSold = SUM(sales.SoldQuantity) 
WHERE sales.ItemCode = products.Code

So which is the correct query to return the accurate results and solve this problem?那么哪个是返回准确结果并解决此问题的正确查询?

You need to aggregate before joining:加入前需要聚合:

UPDATE products p INNER JOIN
       (SELECT s.ItemCode, SUM(s.SoldQuantity) as SoldQuantity
        FROM sales s
        GROUP BY s.ItemCode
       ) s
       ON s.Itemcode = p.Code
    SET p.UnitsSold = s.SoldQuantity;

You can make a subquery for your SUM你可以为你的 SUM 做一个子查询

UPDATE products INNER JOIN sales ON sales.Itemcode = products.Code 
SET products.UnitsSold = (SELECT SUM(sales.SoldQuantity) WHERE sales.ItemCode = products.Code)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM