请帮助解决此问题,
我试图弄清楚如何使用Table1中的QtyToSubtract和Product_ID更新Table2,每次更新Row时重新计算CurrentQty和Balance。
对于表1中的每个ROW,我需要更新表2中的当前数量和余额 使用具有MAX BALANCE的行为该PRODUCT_ID从CurrentQty中减去。 这意味着如果在减去它之后,相同的记录可以多次更新,它仍然保持最大平衡。
Table1保留数量减去:
PRODUCT_ID QTYtoSubtract
11111111 2
11111111 2
11111111 2
22222222 6
22222222 6
表2需要更新
PRODUCT_ID OriginalQTY CurrentQty BALANCE = Initial+ Current
11111111 46 12 58
11111111 15 40 55
22222222 6 1 7
22222222 24 6 28
22222222 15 8 23
结果应该是这样的:
PRODUCT_ID OriginalQTY CurrentQty BALANCE = Initial+ Current
11111111 46 8 54
11111111 15 38 53
22222222 6 1 7
22222222 24 0 22
22222222 15 2 17
答案 0 :(得分:0)
好的,这是CURSOR
似乎是最佳选择的罕见时期之一:
DECLARE @Product_ID VARCHAR(8), @Qty INT
DECLARE CC CURSOR
LOCAL STATIC READ_ONLY FORWARD_ONLY
FOR
SELECT *
FROM Table1
ORDER BY [PRODUCT_ID], [QTYtoSubtract] DESC
OPEN CC
FETCH NEXT FROM CC INTO @Product_ID, @Qty
WHILE @@FETCH_STATUS = 0
BEGIN
WITH CTE AS
(
SELECT *,
RN=ROW_NUMBER() OVER(ORDER BY Balance DESC)
FROM Table2
WHERE PRODUCT_ID = @Product_ID
)
UPDATE CTE
SET BALANCE = BALANCE - @Qty
WHERE RN = 1
FETCH NEXT FROM CC INTO @Product_ID, @Qty
END
CLOSE CC
DEALLOCATE CC
SELECT *
FROM Table2
结果:
╔════════════╦═════════════╦════════════╦═════════╗
║ PRODUCT_ID ║ OriginalQTY ║ CurrentQty ║ BALANCE ║
╠════════════╬═════════════╬════════════╬═════════╣
║ 11111111 ║ 46 ║ 12 ║ 54 ║
║ 11111111 ║ 15 ║ 40 ║ 53 ║
║ 22222222 ║ 6 ║ 1 ║ 7 ║
║ 22222222 ║ 24 ║ 6 ║ 22 ║
║ 22222222 ║ 15 ║ 8 ║ 17 ║
╚════════════╩═════════════╩════════════╩═════════╝