How can one reference a calculated value from the previous row in a SQL query? In my case each row is an event that somehow manipulates the same value from the previous row.
The raw data looks like this:
Eventno Eventtype Totalcharge 3 ACQ 32 2 OUT NULL 1 OUT NULL
Lets say each Eventtype=OUT should half the previous row totalcharge in a column called Remaincharge:
Eventno Eventtype Totalcharge Remaincharge 3 ACQ 32 32 2 OUT NULL 16 1 OUT NULL 8
I've already tried the LAG analytic function but that does not allow me to get a calculated value from the previous row. Tried something like this:
LAG(remaincharge, 1, totalcharge) OVER (PARTITION BY ...) as remaincharge
But this didn't work because remaingcharge could not be found.
Any ideas how to achieve this? Would need a analytics function that can give me the the cumulative sum but given a function instead with access to the previous value.
Thank you in advance!
Update problem description
I'm afraid my example problem was to general, here is a better problem description:
What remains of totalcharge is decided by the ratio of outqty/(previous remainqty).
Eventno Eventtype Totalcharge Remainqty Outqty 4 ACQ 32 100 0 3 OTHER NULL 100 0 2 OUT NULL 60 40 1 OUT NULL 0 60
Eventno Eventtype Totalcharge Remainqty Outqty Remaincharge 4 ACQ 32 100 0 32 3 OTHER NULL 100 0 32 - (0/100 * 32) = 32 2 OUT NULL 60 40 32 - (40/100 * 32) = 12.8 1 OUT NULL 0 60 12.8 - (60/60 * 12.8) = 0