異なるデータベースでは、これを行うさまざまな方法があります。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
すべてのデータベースが 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>