sql - 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
请帮忙,我完全糊涂了。
解决方案
推荐阅读
- python - 沿二维数组中的对角线和对角线求和 - NumPy / Python
- python - 当数据类型为 32 位浮点数时,录制的声音会变得嘈杂/失真
- django - 'ModelBase' 对象不可迭代
- javascript - 使用javascript替换具有hypen的字符串
- ruby-on-rails - Rails 不知从何处添加 API 字段
- php - 在 foreach 循环中及时返回
- sql-server - 全文搜索条件“,”中“,”附近的语法错误
- python-3.x - 如何将画布保存在程序列表中,然后对其进行迭代以显示对象?
- c# - Visual Studio Windows 服务 c# exe 文件丢失
- python - 需要动态地从用户那里获取文件