I have one table as below mysql
customer_id,invoice_id,invoice_month,payment_month,invoice_amount,payment_amt,balance_amt
1,1,"DEC 23","JAN 24",400.00,400.00,0.00
1,2,"DEC 23","JAN 24",600.00,600.00,0.00
1,3,"JAN 24","JAN 24",200.00,50.00,150.00
2,4,"SEP 23","MAY 24",800.00,800.00,0.00
2,5,"OCT 23","MAY 24",750.00,750.00,0.00
3,6,"FEB 24","MAY 24",925.00,525.00,400.00
4,7,"NOV 22","JUN 23",325.00,325.00,0.00
4,8,"DEC 22","JUN 23",425.00,425.00,0.00
5,9,"JUN 24",NULL,500.00,NULL,500.00
Payment table as
customer_id,payment_month,amount
1,JAN 24,500
1,FEB 24,550
2,MAR 24,450
2,APR 24,900
2,MAY 24,450
3,MAY 24,525
4,JUN 23,350
4,JUN 23,400
need to create a new columns payment_final_month based on “payment_month” from the payment table.
For the first record i have invoice amount has 400 which is less than the payment table amount first record then pick JAN 24
For the second record as i have 100 left from the first record then pick the same JAN 24
For 3rd record i should pick the FEB 24
Final output something as
customer_id invoice_id invoice_month payment_month invoice_amount payment_amt balance_amt payment_final_month
1 1 DEC 23 JAN 24 400.00 400.00 0.00 JAN 24
1 2 DEC 23 JAN 24 600.00 600.00 0.00 JAN 24
1 3 JAN 24 FEB 24 200.00 50.00 150.00 FEB 24
2 4 SEP 23 MAR 24 800.00 800.00 0.00 MAR 24
2 5 OCT 23 APR 24 750.00 750.00 0.00 APR 24
3 6 FEB 24 MAY 24 925.00 525.00 400.00 MAY 24
4 7 NOV 22 JUN 23 325.00 325.00 0.00 JUN 23
4 8 DEC 22 JUN 23 425.00 425.00 0.00 JUN 23
5 9 JUN 24 NULL 500.00 NULL 500.00 NULL
I tried below approach and didnt worked
i.invoice_amount - COALESCE(LAG(i.payment_amt, 1) OVER (PARTITION BY i.customer_id ORDER BY i.invoice_id), 0) AS remaining_amount