简体   繁体   English

分组后从两个表中减去列(用于库存)

[英]Subtract columns from two tables after grouping (for inventory)

So for my inventory system I have two tables with the same columns names (one for stock produced and one for stock shipped). 因此,对于我的库存系统,我有两个表具有相同的列名(一个用于生产库存,一个用于装运库存)。 I figured out how to group the columns by the product and then sum the quantities. 我想出了如何按产品对列进行分组,然后对数量求和。 So I want to run this query on both tables then subtract the quantity column from each table where the product variables match up. 因此,我想在两个表上都运行此查询,然后从产品变量匹配的每个表中减去数量列。

I use this to add group and sum stock totals (in): 我用它来添加组和总计存货总额(入):

 $query = "SELECT id, type, color, product, SUM(Quantity) AS TotalQuantity FROM inventory GROUP BY id, color, type";

And I use this to group and sum stock shipments (out): 我用它来对库存发货(出库)进行分组和汇总:

$query = "SELECT id, type, color, product, SUM(Quantity) AS TotalQuantity FROM shipped GROUP BY id, color, type";

So how do I subtract the quantity columns for each of these? 那么我如何减去这些数量列呢?

Edit: 编辑:

I use this for output: (a table) 我将其用于输出:(一个表)

 echo '<tr><td>'. $row['product'] . '</td><td id="replace">' . $row['type'] . '</td><td>' . $row['color']. '</td><td>'. $row['TotalQuantity'];
 echo "</td></tr>";

This can be done entirely in one query. 这可以完全在一个查询中完成。 An INNER JOIN between these will allow you to subtract the quantities. 这些之间的内部INNER JOIN将使您减去数量。 The id, color, product columns are only needed from one of the tables in your SELECT list. 仅从SELECT列表中的表之一中需要id, color, product列。

SELECT
  inv.id, 
  inv.color,
  inv.product,
  /* total inventory quantity */
  SUM(inv.Quantity) AS TotalInvQuantity,
  /* total shipped quantity */
  SUM(ship.Quantity) AS TotalShipQuantity,
  /* inventory quantity minus shipped quantity */
  SUM(inv.Quantity) - COALESCE(SUM(ship.Quantity), 0) AS SubtractedQuantity
FROM
  inventory inv
  LEFT JOIN shipped ship ON inv.id = ship.id AND inv.color = ship.color AND inv.product = ship.product
GROUP BY
  inv.id,
  inv.color,
  inv.product

Update after comments 评论后更新

SELECT
  inv.id,
  inv.color,
  inv.product,
  inv.TotalInvQuantity, 
  COALESCE(ship.TotalShipQuantity, 0) AS TotalShipQuantity,
  inv.TotalQuantity - COALESCE(ship.TotalQuantity, 0) AS SubtractedQuantity
FROM (
    SELECT id, product, color, SUM(Quantity) AS TotalInvQuantity
    FROM inventory
    GROUP BY id, product, color
  ) inv
  LEFT JOIN (
    SELECT id, product, color, SUM(Quantity) AS TotalShipQuantity
    FROM inventory
    GROUP BY id, product, color
  ) ship ON 
      inv.id = ship.id 
      AND inv.product = ship.product 
      AND inv.color = ship.color

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

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