I have a query gets opening and closing balances for each month of customers from their transactions and then get a company total for the month. but if a customer does not have any transactions for multiple months i need to get the last closing and use it to fill all empty months.. right now im using LAG to get the last closing balance before any empty but when i carry that forward i can only carry it forward into 1 empty month which results in incorect calculation of the company’s total… any help will be appreciated.
Question posted in Amazon Web Sevices
The official Amazon Web Services documentation can be found here.
The official Amazon Web Services documentation can be found here.
2
Answers
found that this is line made my query working for anybody that care.
customer_month_balances AS ( -- Combine customer-month combinations with their balances SELECT pm."customer_id", pm."month", COALESCE(mb."month_opening_balance", NULL) AS "month_opening_balance", COALESCE(mb."month_closing_balance", NULL) AS "month_closing_balance" FROM customer_months pm LEFT JOIN monthly_balances mb ON pm."customer_id" = mb."customer_id" AND pm."month" = mb."month" ), propagated_balances AS (
)
I have created sample data and output based on my understanding of the question, but can edit as required.
This shows transactions are missing for customer id 1 for months like February,April etc.
I then created a CTE (
month_series
) which would create all months based on current date for all customers, you can just use a date dimension (if you have one) and generate all the months.The important logic lies in CTE
balances_with_gaps
, which will populate the closing balance for the latest previous month where it was available, that is the reason for usinglt.month <= ms.month
andORDER BY
andLIMIT
Fiddle
You should be mostly able to convert balances_with_gaps CTE in redshift as it supports limit, I used mysql as an example.
Output