我有一个包含表格中库存的表格
ID |Product ID | Movement | Cumulative Quantity | Store ID
=================================================|=========
1 | 1 | 100 | 100 | 1
2 | 1 | -4 | 96 | 1
3 | 1 | -1 | 95 | 1
4 | 2 | 100 | 100 | 1
5 | 1 | 100 | 100 | 2
每一行基本上都有库存变动,最后一行 MAX(ID) 包含 cumulative_quantity,其中包含可用库存
另一个包含产品的表
ID | Product Name
====================
1 | Apple Juice
2 | Orange Juice
我正在寻找表单中的输出
Product ID | Product Name | Total Quantity at all stores
========================================================
1 | Apple Juice | 195
2 | Orange Juice | 100
这是下表的简化版本
Store ID | Product ID | Product Name | Cumulative Quantity
========================================================
1 | 1 | Apple Juice | 95
1 | 2 | Orange Juice | 100
2 | 1 | Apple Juice | 100
2 | 2 | Orange Juice | 0
最佳答案
这是一个相对简单的 SUM()
聚合,带有一个 JOIN
。 SUM(Movement)
将得出所有商店可用的总数量。
SELECT
inventories.productId,
productName,
SUM(Movement) AS `Total Quantity`
FROM inventories JOIN products ON inventories.productId = products.productId
GROUP BY inventories.productId, productName
关于包含连接的子查询的MySQL总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7688302/