如何将记录汇总到极限

时间:2014-12-12 00:43:04

标签: sql-server sql-server-2008 sql-update sum

我有一张桌子

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的逻辑:

  1. 现在我总是需要CorrectAmount为350(硬编码)
  2. 的总和
  3. 将“正确金额”保持为“金额”,直到350
  4. 从最高记录开始,直至达到350。
  5. 预期结果:

    #tableA

    PID  Amount CorrectAmount
    -------------------------
    1     100     100
    2     100     100
    3     100     100
    4     100     50
    5     100     0
    

1 个答案:

答案 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