如何使用先前的单元格值更新单元格值+另一个单元格值

时间:2016-12-19 22:20:39

标签: c# sql-server tsql sql-update

我的项目在服务器端有SQL脚本问题。 我正在尝试设置付款。 1

问题是,当客户未支付当天付款时,PayedAmount中会有“0”,Status = 2,但差值必须为上一个值加上PaymentAmount值。我可以用1排,1个积分来做到这一点,但我不知道如何与几个客户这样做。如何更新所有这些值?

对不起我的英语,如果可以,请帮助我

1 个答案:

答案 0 :(得分:0)

看看我的解决方案。

CREATE TABLE #Temp
(
    Id              INT,
    CreditId        INT,
    PaymentDay      INT,
    PaymentAmount   MONEY,
    PayedAmount     MONEY,
    [Status]        INT,
    PayedOn         DATETIME,
    Different       MONEY
)

INSERT #Temp
VALUES
    (38827, 37219, DATEDIFF(DAY, '', '2016-12-19'), 249.2308, 100.0000, 1, CAST('2016-12-19 14:12:07' AS DATETIME), 149.2308),
    (38828, 37219, DATEDIFF(DAY, '', '2016-12-22'), 249.2308, 0.0000, 0, NULL, 0),
    (38829, 37219, DATEDIFF(DAY, '', '2016-12-25'), 249.2308, 0.0000, 0, NULL, 0),
    (38830, 37219, DATEDIFF(DAY, '', '2016-12-26'), 249.2308, 0.0000, 0, NULL, 0),

    (38837, 37220, DATEDIFF(DAY, '', '2016-12-19'), 249.2308, 100.0000, 1, CAST('2016-12-19 14:12:07' AS DATETIME), 149.2308),
    (38838, 37220, DATEDIFF(DAY, '', '2016-12-22'), 200, 90.0000, 0, NULL, 0),
    (38839, 37220, DATEDIFF(DAY, '', '2016-12-25'), 200, 0.0000, 0, NULL, 0),
    (38840, 37220, DATEDIFF(DAY, '', '2016-12-26'), 200, 0.0000, 0, NULL, 0)

;WITH cte1
AS
( 
    SELECT ROW_NUMBER() OVER(PARTITION BY t.CreditId ORDER BY t.Id) AS RowNumber, t.*
    FROM #Temp t
),
cte
AS
(
    SELECT RowNumber, Id, CreditId, PaymentAmount - PayedAmount AS Different
    FROM cte1
    WHERE RowNumber = 1

    UNION ALL

    SELECT t.RowNumber, t.Id, t.CreditId, cte.Different + t.PaymentAmount - t.PayedAmount
    FROM cte
        JOIN cte1 t ON t.RowNumber = cte.RowNumber + 1 AND t.CreditId = cte.CreditId
    WHERE t.RowNumber > 1

)

UPDATE t
SET Different = cte.Different
FROM #Temp t
    JOIN cte ON cte.Id = t.Id

SELECT * FROM #Temp

DROP TABLE #Temp