不知道这是否可以单独使用sql来完成,但是我想问一下,然后在过程中添加另一个步骤。
举例来说,我有一组虚拟订单
+----------+-------------+----------+----------+-----------------+-----+ | Supplier | Destination | Req_Time | Prd_Code | Prd_Description | Qty | +----------+-------------+----------+----------+-----------------+-----+ | A | B | 01:00 | 1 | Chair | 100 | | A | B | 01:00 | 2 | Desk | 50 | | A | B | 01:00 | 3 | Phone | 20 | | A | B | 05:00 | 1 | Chair | 200 | | A | B | 05:00 | 2 | Desk | 20 | +----------+-------------+----------+----------+-----------------+-----+
和当前的库存清单
+----------+----------+----------+-------+ | Supplier | Prd_Code | Prd_Desc | Stock | +----------+----------+----------+-------+ | A | 1 | Chair | 150 | | A | 2 | Desk | 40 | | A | 3 | Phone | 100 | +----------+----------+----------+-------+
有没有办法我可以生成一个存储过程(SQL 2008-Compatible),该存储过程可以减去我所拥有的库存,而让我留下需要的东西,就像这样
+----------+-------------+----------+----------+-----------------+-----+ | Supplier | Destination | Req_Time | Prd_Code | Prd_Description | Qty | +----------+-------------+----------+----------+-----------------+-----+ | A | B | 01:00 | 2 | Desk | 10 | | A | B | 05:00 | 1 | Chair | 150 | | A | B | 05:00 | 2 | Desk | 20 | +----------+-------------+----------+----------+-----------------+-----+
我想向您展示我的尝试,但是在这种情况下,我不知道从哪里开始。
PS必须感谢此站点非常轻松地为我格式化了表格 https://ozh.github.io/ascii-tables/
会更感激任何见解和任何例子:D
我没有SQL Server,并且SQLFiddle最近与我的配合不好,因此未经测试,但是逻辑应该可以工作…
WITH stock_changes AS ( SELECT Supplier, Destination, Req_Time, Prd_Code, Prd_Description, -Qty AS Qty FROM orders UNION ALL SELECT Supplier, NULL, '00:00', Prd_Code, Prd_Desc, Stock FROM stock ), stock_post_order AS ( SELECT *, SUM(Qty) OVER (PARTITION BY Supplier, Prd_Code ORDER BY Req_Time ROWS UNBOUNDED PRECEDING ) AS new_qty FROM stock_changes ) SELECT *, CASE WHEN new_qty > qty THEN new_qty ELSE qty END AS order_shortfall FROM stock_post_order WHERE new_qty < 0
首先将您的订单数量反转为负,因此它们就是库存水平将要改变的数量。
接下来,将您的库存水平与订单结合起来,所需时间为0 (使其有点像交付库存而不是库存的订单,并且先于所有其他订单) 。
接下来,计算出订购后产品的总剩余数量;通过汇总该产品的所有先前行(按时间顺序)。 (给予Stock - Order1 - Order2, etc, etc)
Stock - Order1 - Order2, etc, etc
然后选择新库存水平为负的行。