首页 > 解决方案 > SQL Server:如何使用 ExpireTime 正确计算余额?

问题描述

有必要计算某个日期的奖金余额,同时考虑到每笔交易的奖金有效期。LifeTime术语在ExpireTime列中。类型 10 - 加交易,类型 20 - 减交易。到时ExpireTime,奖金应该到期。

类型 交易时间 奖金总额 过期时间
10 2021-03-22 15:27:03.270 4608,00 2022-03-22 15:27:03.270
10 2021-03-22 15:41:04.553 4608,00 2022-03-22 15:41:04.553
20 2021-03-24 18:20:12.423 -3,50 2099-01-01 00:00:00.000
10 2021-03-24 18:20:12.423 2508,00 2022-03-24 18:20:12.423
10 2021-03-24 18:20:12.423 1000,00 2021-04-03 18:20:12.423
10 2021-03-24 18:20:12.423 1200,00 2021-04-02 18:20:12.423
10 2021-03-24 18:20:12.423 1380,00 2021-03-31 18:20:12.423
20 2021-03-25 09:20:12.423 -2200,00 2099-03-24 18:20:12.423
20 2021-03-25 10:07:26.123 -3,50 2099-01-01 00:00:00.000
10 2021-03-25 10:07:26.140 2508,00 2022-03-25 10:07:26.140
10 2021-03-25 10:07:26.140 1000,00 2021-04-04 10:07:26.140
10 2021-03-25 10:07:26.140 1200,00 2021-04-03 10:07:26.140
10 2021-03-25 10:07:26.140 1380,00 2021-04-01 10:07:26.140

我的第一个想法是:

declare @BalanceDate datetime  = getdate()

select sum(BonusSum)
from BonusTransaction
where ExpireTime > @BalanceDate

但这不是真的,因为它没有考虑到奖金在收到余额之前可能已经贷记和借记。

然后我尝试了这样的事情:

select 
    sum (case when (ExpireTime > @BalanceDate and [Checkx] = 10) then BonusSum end) - 
    sum(case when  Checkx = 20 then BonusSum  end) -
    sum(case when (ExpireTime < @BalanceDate and [Checkx] = 10) then BonusSum  end)
from 
    BonusTransaction

但这也不是真的。我也尝试使用类似这样的窗口函数:

select max(Sum) as Balance 
from
    (select sum(BonusSum) over (order by [TimeInsert] rows between unbounded preceding and current row) as Sum
     from BonusTransaction) t

请帮忙,我完全糊涂了。

标签: sqlsql-serverfunction

解决方案


推荐阅读