I need to find change in some account within some period. Assume I have several accounts and money comes and goes. I need to find starting sum and ending sum along with difference for each unique accounts for november 2020 year.
I have a table like below:
--------------------------------------------------------------------------------------------
code_filial | oper_day | code_account | sum_in | sum_out |
--------------------------------------------------------------------------------------------
00116 | 2020-05-12 | 1740100126 | 187322000 | 210522000 |
00116 | 2020-05-14 | 1740100126 | 210522000 | 256582000 |
00116 | 2020-11-04 | 1740100250 | 2000000 | 52050 |
00116 | 2020-11-05 | 1740100250 | 52050 | 2872050 |
00116 | 2020-11-14 | 1740100250 | 2872050 | 5855000 |
00116 | 2020-11-30 | 1740100250 | 5855000 | 7837000 |
00116 | 2020-12-03 | 1740100250 | 7837000 | 4900000 |
Result should look like below:
-------------------------------------------------------------------------------------------------------
code_filial | oper_day | code_account | sum_in | sum_out | diffrence
-------------------------------------------------------------------------------------------------------
00116 | 2020-05-14 | 1740100126 | 256582000 | 256582000 | 256582000
00116 | 2020-11-04 | 1740100250 | 2000000 | 7837000 | 5837000
For example 256582000 account, in this account no process has been done in november 2020, so that I need to take last sum_out as sum_in and sum_out, difference would be also same. But in case 1740100250 account, in this account some operations has been done, on 2020-11-04 date,first date in november, sum_in started with 2000000 and on last day of november 2020-11-30 sum_out was 7837000, difference would be 7837000 - 2000000 = 5837000. I tried some ways but cannot make the logic.