Development resources, articles, tutorials, code samples, tools and downloads for ASP.Net, SQL Server, Reporting Services, T-SQL, Windows, AWS, SAP HANA and ABAP
SQL Tutorial - How to Map Payments to Expenses using T-SQL Query
Problem Statement:
In your SQL Server database you have two database tables to store expenses and payments for closing expense amount.
You want to list the expenses of a customer using t-sql by querying your sql tables.
This list will also add the payments done by the same customer to close these expenses.
Each payment will be listed as new columns beside the expenses records.
Here is sql script for creating sample data for our sql problem.
The tsql script contains CREATE TABLE statements which creates sql tables in database to store expenses and payments data.
The below t-sql script maps each payment to an expense entry.
The payment to expense mapping is managed by t-sql select statement in an order according to Payment date and Expense date.
If partial payments are done, the below t-sql script handles this situation and decreases the amount to be paid by the payment amount.
And the following payment in date order is used to close the current expense amount.
If the payment amount is more than the expense amount, this extra payment amount is used for the payment of the next expense.
The following payment to expenses sql script will handle this situation also.
The output of the above t-sql CTE query will result as follows :