我有一张桌子
CREATE TBALE #tableA (PID int, Amount decimal (10,2), CorrectAmount decimal(10,2))
INSERT INTO #TableA (PID, Amount)
VALUES (1,100), (2,100), (3,100), (4,100), (5,100)
填充correctAmount
的逻辑:
CorrectAmount
为350(硬编码)预期结果:
#tableA
:
PID Amount CorrectAmount
-------------------------
1 100 100
2 100 100
3 100 100
4 100 50
5 100 0
答案 0 :(得分:1)
;WITH Joined as(
SELECT
t1.PID,
t1.Amount,
RunningTotal = SUM(t2.Amount),
PrevRunningTotal = SUM(t2.Amount) - t1.Amount,
rn = ROW_NUMBER() OVER(ORDER BY SUM(t2.Amount))
FROM #tableA t1
INNER JOIN #tableA t2
ON t2.PID <= t1.PID
GROUP BY
t1.PID, t1.Amount
HAVING
SUM(t2.Amount) > 350
)
UPDATE t
SET t.CorrectAmount =
CASE
WHEN j.PID IS NULL THEN t.Amount
ELSE
CASE
WHEN j.rn = 1 THEN 350 - j.PrevRunningTotal
ELSE 0
END
END
FROM #tableA t
LEFT JOIN Joined j ON j.PID = t.PID