PostgreSQL中的条件累积和

时间:2017-08-21 11:24:04

标签: postgresql window-functions cumulative-sum

我有一张表有游戏分数。每个玩家都有一些游戏在一个或多个会话中进行,并在这些会话中按顺序排列。

create table games (
  player int, 
  session int,
  ord int,
  score int
 );

 insert into 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 |
+--------+---------+-----+---------+

我希望负分数在每个会话中级联,以便从未来的分数中扣除它们,直到它们被完全记录。不同会话中的分数不应相互影响,正分数不应下降

简单地说,我需要条件累积和,只影响负数。

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

0 个答案:

没有答案