簡體   English   中英

分組后從兩個表中減去列(用於庫存)

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

因此,對於我的庫存系統,我有兩個表具有相同的列名(一個用於生產庫存,一個用於裝運庫存)。 我想出了如何按產品對列進行分組,然后對數量求和。 因此,我想在兩個表上都運行此查詢,然后從產品變量匹配的每個表中減去數量列。

我用它來添加組和總計存貨總額(入):

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

我用它來對庫存發貨(出庫)進行分組和匯總:

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

那么我如何減去這些數量列呢?

編輯:

我將其用於輸出:(一個表)

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

這可以完全在一個查詢中完成。 這些之間的內部INNER JOIN將使您減去數量。 僅從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

評論后更新

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