I've got the following data (Table 1) and I want to calculate the balance at the end of each Gaming Date. However, when the Date Redeemed is less than the Gaming Date that means the amount needs to be subtracted from the ending balance. How do I write a statement that is looking at the Gaming Date in a specific row and the Date Redeemed in ALL previous rows and takes the sum amount of the rows where the Gaming Date is greater that the Date Redeemed (Table 2) Table2
Table1
DateRedeemed GamingDate Trip Amount
13/07/2017 03/07/2017 8001 100
17/07/2017 03/07/2017 8001 150
18/07/2017 04/07/2017 8001 125
27/07/2017 16/07/2017 8001 250
28/07/2017 16/07/2017 8001 310
27/07/2017 17/07/2017 8001 125
31/07/2017 18/07/2017 8001 75
28/07/2017 27/07/2017 8001 80
31/07/2017 28/07/2017 8001 100
Table 2
DateRedeemed GamingDate Trip Amount Running
13/07/2017 03/07/2017 8001 100 100
17/07/2017 03/07/2017 8001 150 250
18/07/2017 04/07/2017 8001 125 375
27/07/2017 16/07/2017 8001 250 525
28/07/2017 16/07/2017 8001 310 835
27/07/2017 17/07/2017 8001 125 810
31/07/2017 18/07/2017 8001 75 760
28/07/2017 27/07/2017 8001 80 590
31/07/2017 28/07/2017 8001 100 610
select *, amount - sum(amount) over (order by GamingDate)
or some variation. – S3S