I have invoicing solution that uses Azure SQL to store and calculate invoice data. I have been requested to provide 'credit' functionality so rather than recovering customers charges, the totals are deducted from an amount of available credit and reflected in the invoice (solution xyz may have 1500 worth of charges, but deducted from available credit of 10,000 means its effectively zero'd and leaves 8,500 credit remaining ). Unfortunately after several days I haven't been able to work out how to do this.
I am able to get a list of items and their costs from sql easily:
invoice_id | contact_id | solution_id | total | date |
---|---|---|---|---|
202104-015 | 52 | 10000 | 30317.27 | 2021-05-22 |
202104-015 | 52 | 10001 | 2399.90 | 2021-05-22 |
202104-015 | 52 | 10005 | 8302.27 | 2021-05-22 |
202104-015 | 52 | 10060 | 3625.22 | 2021-05-22 |
202104-015 | 52 | 10111 | 22.87 | 2021-05-22 |
202104-015 | 52 | 10115 | 435.99 | 2021-05-22 |
I have another table that shows the credit available for the given contact:
id | credit_id | owner_id | total_applied | date_applied |
---|---|---|---|---|
1 | C00001 | 52 | 500000.00 | 2021-05-14 |
I have tried using the following SQL statement, based on another stackoverflow question to subtract from the previous row, thinking each row would then reflect the remaining credit:
Select
invoice_id,
solution_id
sum(total) as 'total',
cr.total_remaining - coalesce(lag(total)) over (order by s.solution_id), 0) as credit_available,
date
from
invoices
left join credits cr on
cr.credit_id = 'C00001'
Whilst this does subtract, it only subtracts from the row above it, not all of the rows above it:
invoice_id | solution_id | total | credit_available | date |
---|---|---|---|---|
202104-015 | 10000 | 30317.27 | 500000.00 | 2021-05-22 |
202104-015 | 10001 | 2399.90 | 469682.73 | 2021-05-22 |
202104-015 | 10005 | 8302.27 | 497600.10 | 2021-05-22 |
202104-015 | 10060 | 3625.22 | 491697.73 | 2021-05-22 |
202104-015 | 10111 | 22.87 | 496374.78 | 2021-05-22 |
202104-015 | 10115 | 435.99 | 499977.13 | 2021-05-22 |
I've also tried various queries with a mess of case statements.
Im at the point where I am contemplating using powershell or similar to do the task instead (loop through each solution, check if there is enough available credit, update a deduction table, goto next etc) but I'd rather keep it all in SQL if I can.
Anyone have some pointers for this beginner?