T-SQL查找金额何时达到设定值

时间:2016-07-25 14:07:03

标签: c# sql sql-server

我有一个包含以下数据的表:

ID  Amount  Status
1   15.00   Paid
2   3.00    Paid
3   10.00   Awaiting
4   12.00   Awaiting

系统查看此表以查看客户是否已为订阅支付了足够的费用。这使用表来记录付款。每天一次,我需要查看客户是否满足此要求。

解决方案与上表完全不同,因为它更复杂,但问题仍然存在,可以分解为此。

我需要找到一种方法来增加金额,但当金额超过20时,更改表格中的数据如下:

ID  Amount  Status
1   15.00   Paid
2   3.00    Paid
3   2.00    Paid               <= Customer has reached payment level
4   12.00   Cancelled          <= Subsequent payment is cancelled
5   8.00    BForward           <= Extra money is brought forward

目前我正在使用游标,但性能不好,正如预期的那样。

有没有人知道更好的方法?

1 个答案:

答案 0 :(得分:0)

生成所需的结果。不确定为什么要更新原始数据(假设这是跨国数据)

Declare @Table table (ID int,Amount money,Status varchar(50))
Insert into @Table values
(1,15.00,'Paid'),
(2,3.00,'Paid'),
(3,10.00,'Awaiting'),
(4,12.00,'Awaiting')

;with cteBase as (
    Select *
          ,SumTotal=sum(Amount) over (Order By ID) 
     From  @Table
), cteExtended as (
    Select *
          ,Forward   = IIF(SumTotal>20 and SumTotal-Amount<20,SumTotal-20,0)
          ,Cancelled = IIF(SumTotal>20 and SumTotal-Amount>20,Amount,0)
     From cteBase
)
Select ID,Amount,Status='Paid' from cteExtended Where Forward+Cancelled=0
Union All
Select ID,Amount=Amount-Forward,Status='Paid' from cteExtended Where Forward>0
Union All
Select ID,Amount,Status='Cancelled' from cteExtended Where Cancelled>0
Union All
Select ID=(Select Count(*) from cteBase)+Row_Number() over (Order by ID),Amount=Forward,Status='BForward' from cteExtended Where Forward>0
Order By ID

返回

ID  Amount  Status
1   15.00   Paid
2   3.00    Paid
3   2.00    Paid
4   12.00   Cancelled
5   8.00    BForward