I have a data set similar to the one below. What I'm trying (and failing) to do is calculate the number of days past due each payment is on any given day between the first payment and today.
But here's the catch, each amount paid must be deducted from the earliest amount due first then anything left over will be deducted from the next amount due.
So in the example below the earliest payment overdue would be row 1 until this is fully paid, which is on the 26/08/16 then row 4 would become the earliest payment overdue. This is because the cumulative amounts paid up to an including the 26/08/16 would be £2656.15 which would cover amounts due on rows 1,2 and 3.
RowNumber AccountNumber date AmountDue AmountPaid
1 1000 05/11/2015 1422.5 0
2 1000 26/11/2015 474.17 0
3 1000 26/12/2015 474.17 0
4 1000 26/01/2016 474.17 0
5 1000 26/02/2016 474.17 400.31
6 1000 26/03/2016 474.17 474.17
7 1000 26/04/2016 474.17 0
8 1000 26/05/2016 474.17 0
9 1000 26/06/2016 474.17 474.17
10 1000 26/07/2016 474.17 0
11 1000 26/08/2016 474.17 1307.5
12 1000 26/09/2016 474.17 0
13 1000 26/10/2016 474.17 0
14 1000 26/11/2016 474.17 434.17
15 1000 26/12/2016 474.17 434.17
16 1000 26/01/2017 474.17 0
Any help would be very much appreciated!
Best Answer
The way I solved this was assembling these pieces:
Using a cte with running totals for
AmountDue
andAmountPaid
Using
outer apply()
to get the earliest paid date and final days overdue for each account using the running totalsDaysOverDue
is either the final amount of days overdue as of the day it was completley paid off, or if not yet paid off, as of@Date
which is set as current date in the query below.PaidDate
is the first date for an account where theRunningAmountPaid >= RunningAmountDue
update from comment based on additional issue not in the original question:
Added an
outer apply()
in thecte
to check if the next row for an account had a negative value forAmountPaid
and if so, added that to theRunningAmountPaid
.This cleared up the issue of an amount being marked as paid when the next transaction was a reversal of the previous payment.
rextester link: http://rextester.com/YTHG73937
test setup:
query:
results: