我们会在不同日期向客户收取账单,并且会以不定期的方式收取款项。我们需要计算付款延迟天数,直到收到特定付款到期的全额付款为止。数据是仅一个客户端0123
table Due (id, fil varchar(12), amount numeric(10, 2), date DATE)
table Received (id, fil varchar(12), amount numeric(10, 2), date DATE)
到期表:
id fil amount date
----------------------------------------
1. 0123 1000. 2019-jan-01
2. 0123 1500 2019-jan-15
3. 0123 1200. 2019-jan-25
4. 0123 1800. 2019-feb-10
表Received
:
id. fil. amount. date
-----------------------------------------
1. 0123 1000. 2019-jan-10
2. 0123 500. 2019-jan-20
3. 0123 1300. 2019-jan-25
4. 0123 400. 2019-feb-08
5. 0123 1000. 2019-feb-20
联接表应显示:
fil. due_date due_amount. received_amount date delay
------------------------------------------------------------------------
0123 2019-jan-01 1000. 1000 9
0123 2019-jan-15. 1500. 500
0123 1300. 10(since payment completed on 25th jan)
0123 2019-jan-25. 1200. 400.
0123 1000. 26
0123 2019-feb-10. 1800.
我已尽力使计算尽可能准确……如果出现广告错误,请原谅。我只是来写一个脚本来做到这一点,但是也许有人可以建议一个合适的联接。
感谢您的尝试。
答案 0 :(得分:1)
正如@DavidHempy所说,这是不可能的,除非知道每笔付款是针对哪张发票。您可以计算自帐户为零以来已经过了多少天,这可能会有所帮助:
with all_activity as (
select due.date,
-1 * amount as amount
from due
union all
select received.date,
amount
from received),
totals as (
select date,
amount,
sum(amount) over (order by date),
case when sum(amount) over (order by date) >=0
then true
else false
end as nothing_owed
from all_activity)
select date,
amount,
sum,
date - max(date) filter (where nothing_owed = true) OVER (order by date)
as days_since_positive
from totals order by 1
;
date | amount | sum | days_since_positive
------------+----------+----------+---------------------
2019-01-01 | -1000.00 | -1000.00 |
2019-01-10 | 1000.00 | 0.00 | 0
2019-01-15 | -1500.00 | -1500.00 | 5
2019-01-20 | 500.00 | -1000.00 | 10
2019-01-25 | -1200.00 | -900.00 | 15
2019-01-25 | 1300.00 | -900.00 | 15
2019-02-08 | 400.00 | -500.00 | 29
2019-02-10 | -1800.00 | -2300.00 | 31
2019-02-20 | 1000.00 | -1300.00 | 41
(9 rows)
您可以扩展此逻辑以找出它们从0开始的最后截止日期。