sqlamazon-web-servicesamazon-redshift

Carrying forward SQL


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.


Solution

  • 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 (
        
        SELECT
            customer_id,
            month,
            month_opening_balance,
            month_closing_balance,
            LAST_VALUE(month_closing_balance IGNORE NULLS) OVER (
                PARTITION BY customer_id
                ORDER BY month ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
            ) AS propagated_closing_balance
        FROM
            customer_month_balances
    )