window functions - Conditional cumulative sum in PostgreSQL -


i have table of has scores games. each player has number of games come within 1 or more sessions , arranged in order within these sessions.

create table games (   player int,    session int,   ord int,   score int  );   insert games (player, session, ord, score)  values    ('1', '1', '1', '3'),    ('1', '1', '1', '-5'),    ('1', '1', '2', '1'),    ('1', '1', '3', '3'),    ('2', '1', '1', '1'),    ('2', '1', '2', '2'),    ('2', '2', '1', '-2'),    ('2', '2', '2', '3'),    ('2', '2', '3', '2');    +--------+---------+-----+---------+ | player | session | ord |  score  | +--------+---------+-----+---------+ |      1 |       1 |   1 |       3 | |      1 |       1 |   2 |      -5 | |      1 |       1 |   3 |       1 | |      1 |       1 |   4 |       3 | |      2 |       1 |   1 |       1 | |      2 |       1 |   2 |       2 | |      2 |       2 |   1 |      -2 | |      2 |       2 |   2 |       3 | |      2 |       2 |   3 |       2 | +--------+---------+-----+---------+ 

i negative scores cascade down within each session deducted future scores until accounted. scores in different sessions should not affect each other , positive scores should not cascade down.

to put concisely, need conditional cumulative sum affects negative numbers.

+--------+---------+-----+-------+--------+ | player | session | ord | score | target | +--------+---------+-----+-------+--------+ |      1 |       1 |   1 |     3 |      3 | |      1 |       1 |   2 |    -5 |     -5 | no cumulation because previous score positive |      1 |       1 |   3 |     1 |     -4 | 1-5=-4 |      1 |       1 |   4 |     3 |     -1 | 3-4=-1 cumulation because previous score negative after cascading negative scores |      2 |       1 |   1 |     1 |      1 | |      2 |       1 |   2 |     2 |      2 | no cumulation because previous score positive |      2 |       2 |   1 |    -2 |     -2 |  |      2 |       2 |   2 |     3 |      1 | 3-2=1 |      2 |       2 |   3 |     2 |      2 | no cumulation because previous score positive +--------+---------+-----+-------+--------+ 


Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -