我有一个表格,其中包含
形式的库存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
答案 0 :(得分:3)
这是一个相对简单的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
答案 1 :(得分:2)
有几种方法可以做到这一点
使用MAX
在From子句中进行子查询SELECT products.id as `Product ID`,
products.`Product Name`,
SUM(inventory.`Cumulative Quantity`) as Total Quantity at all stores
FROM products
INNER JOIN inventory
ON products.`id` = inventory.`id`
INNER JOIN
(
SELECT ( max(`id`) as `id`,
`product id`,
`store id`
FROM
`inventory`
GROUP BY
`product id`,
`store id`) maxinventory
ON inventory.`id` = maxinventory.`id`
GROUP BY
products.`id`,
products.`Product Name`
这是另一个使用IN
SELECT products.id as `Product ID`,
products.`Product Name`,
SUM(inventory.`Cumulative Quantity`) as Total Quantity at all stores
FROM products
INNER JOIN inventory
ON products.`id` = inventory.`id`
WHERE
inventory.`id ` IN
(
SELECT ( max(`id`) as `id`,
FROM
`inventory`
GROUP BY
`product id`,
`store id`)
GROUP BY
products.`id`,
products.`Product Name`
答案 2 :(得分:0)
诀窍是使用子查询来查找当前的库存记录,即每个id
对的最大product_id, store_id
个库存记录:
SELECT
product_id, name, SUM( cumulative_qty ) AS total_qty
FROM
(SELECT MAX(id) AS id FROM inventories GROUP BY product_id, store_id) AS cur
NATURAL JOIN inventories
JOIN products ON products.id = inventories.product_id
GROUP BY product_id
(顺便说一句,我怀疑你想要inventories (product_id, store_id, id)
上的索引来使这个查询合理有效。当然我假设id
列是主键。)