gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:30:17 26 4
gpt4 key购买 nike

因此,对于我的库存系统,我有两个列名相同的表(一个用于生产的库存,一个用于发货的库存)。我想出了如何按产品对列进行分组,然后对数量求和。所以我想在两个表上运行此查询,然后从产品变量匹配的每个表中减去数量列。

我用它来添加组和求和股票总数(in):

 $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 将允许您减去数量。 id、color、product 列仅需要来自 SELECT 列表中的一个表。

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

关于php - 分组后从两个表中减去列(用于库存),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11068495/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com