在不同的数据库中会有不同的方法来做到这一点。我在 Firebird 2.5 中创建了一个包含您的值的表(仅添加了一个 ID 列并由于保留字而更改了名称)并运行了以下语句:
with recursive tmp_payment (paid) as
(select -sum(amount)
from account_receivables
where amount < 0),
MyResultSet(id, MyBalance, RemainingCredit, Days) as
(select r.id, case when r.amount > p.paid then r.amount-p.paid end,
case when r.amount < 0 then p.paid
when r.amount < p.paid then p.paid-r.amount
else 0 end, current_date - MyDate
from account_receivables r
cross join tmp_payment p
where not exists(select 1 from account_receivables r2 where r2.id < r.id)
union all
select r3.id, case when r3.amount > rs.RemainingCredit then r3.amount - rs.RemainingCredit end,
case when r3.amount < 0 then rs.RemainingCredit
when r3.amount < rs.RemainingCredit then rs.RemainingCredit - r3.amount
else 0 end,
current_date - MyDate
from ACCOUNT_RECEIVABLES r3
join MyResultSet rs on r3.id = rs.id+1)
Select id, MyBalance, Days
from MyResultSet
union all
select null, (select sum(MyBalance) from MyResultSet), null
from rdb$database
除了 rdb$database,它只是一张保证在 Firebird 和 InterBase 中只包含一条记录的表,可能还有 CURRENT_DATE(显而易见的含义),这应该是非常标准的 SQL,尽管远非所有数据库都支持 WITH RECURSIVE(对于MyResultSet, tmp_Payment 不是递归的),有些可能有不同的方法从另一个日期减去一个日期。
这是语句返回的内容:
ID MYBALANCE DAYS
1 <NULL> 110
2 <NULL> 21
3 155.00 20
4 518.21 16
5 <NULL> 16
<NULL> 673.21 <NULL>