[英]SQL Aging Report
我有以下應收帳款的數據交易:
我需要每3天獲得一份賬齡報告,因此腳本應采用最近的付款或信用額度並將其應用於最后的費用。 因此結果將是這樣的:
此處$ 245的信用額適用於最后的$ 400費用,因此該費用的余額為$ 155。 然后,腳本應采用下一個最后的付款方式,並按照如下相同的規則進行應用:
此處,1300美元的付款將應用於4月2日的剩余155美元余額,然后將剩余的1145美元應用於7月1日的1300筆費用,因此期末余額為155美元,導致:
因此,現在我知道最終余額為$ 673.21,但我也知道在0-16天之間,我的未結余額為518.21,在17-30天之間,我的余額為155。
關於如何執行SQL查詢以獲得此結果的任何線索?
非常感謝!! 並感謝您的幫助。
在不同的數據庫中將有不同的方法來執行此操作。 我在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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.