Consider the following 2 tables:
TABLE A:
PIN | ENCOUNTER | BALANCE | REFERENCE_DATE
------------------------------------------
P1 | ABC | 100 | 11-19-2014
P1 | HJI | 300 | 11-20-2014
P1 | PIY | 700 | 11-21-2014
P2 | CDO | 200 | 11-20-2014
P2 | NHG | 200 | 11-21-2014
P3 | CVB | 500 | 11-20-2014
P3 | SJK | 100 | 11-21-2014
TABLE B:
PIN | DEPOSIT
-------------
P1 | 1000
P2 | 400
P3 | 100
Initially Table B
's DEPOSIT
value is to be subtracted from the BALANCE
in table A
with the earliest REFERENCE_DATE
matched by the PIN
. Should the difference be greater than 0, it would be subtracted from the BALANCE
in the next row until the remaining DEPOSIT
becomes less than or equal to 0.
The result after subtracting the deposit from the balances would look like this. I've included another column wherein the deposits are divided per encounter:
PIN | ENCOUNTER | BALANCE | REFERENCE_DATE | DEPOSITS_BREAKDOWN
---------------------------------------------------------------
P1 | ABC | 0 | 11-19-2014 | 100
P1 | HJI | 0 | 11-20-2014 | 300
P1 | PIY | 100 | 11-21-2014 | 600
P2 | CDO | 0 | 11-20-2014 | 200
P2 | NHG | 0 | 11-21-2014 | 200
P3 | CVB | 400 | 11-20-2014 | 100
P3 | SJK | 100 | 11-21-2014 | 0
My Postgres version is 9.3. I'm struggling to formulate the query for this one.