假设我有下表:
production(rec_ID, item_ID, date, qty)
usage(rec_ID, item_ID, date, qty)
inventory(item_ID, stock)
使用以下示例数据:
Production
Rec_ID | item_ID | date | qty
1 | A | 2016-01-18 | 50
2 | A | 2016-01-19 | 50
3 | A | 2016-01-20 | 50
Usage
Rec_ID | item_ID | date | qty
100 | A | 2016-01-20 | 70
Inventory
item_ID| stock
A | 80
正如您所看到的,生产中的任何内容都会增加库存,而使用中的任何内容都会减少库存。现在我有80件库存A,我想查询表生产中哪一行有剩余库存。规则是:早生产的先用完。
使用 ID 100 将首先从生产 ID 1 中获取 (70 - 50)。剩余 20 个将从生产 ID 2 中取出。因此,剩余库存为:80 个(30 个来自生产 ID 2,50 个来自生产 ID 3)。如何根据库存获取生产表中受影响的行?我在想这样的事情:
SELECT * FROM production ORDER BY date DESC
循环添加数量的商品,直到达到当前库存水平。例如:
current_Stock = SELECT stock FROM Inventory WHERE item_ID='A'
production_List = SELECT * FROM production WHERE item_ID='A' ORDER BY date DESC
for each production in production_List
qty_total += production.qty
(add each production to arraylist or something)
if qty_total >= current_Stock
exit for
end if
next
(process affected rows...)
是否有更优雅的方式用纯 SQL 来完成此操作?
最佳答案
这个查询可能是一个解决方案
SELECT NULL AS Rec_ID,
qty,
NULL AS total,
`date`
FROM cc
WHERE (@total := 0)
UNION
SELECT Rec_ID, qty, @total := @total + qty AS total, `date`
FROM
(SELECT *
FROM Production
ORDER BY `date` DESC
WHERE item_ID='A') tmp
WHERE @total <
(SELECT stock
FROM Inventory
WHERE item_ID='A') ;
fiddle 是 http://sqlfiddle.com/#!9/95b3a/1
关于MySQL 根据库存水平搜索受影响的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34905620/