2

我有一张桌子,上面有球员和他们的分数。我设法创建了一个查询来获取累积总和。我希望查询按玩家对这个累积总和进行分组,以便不包括以前玩家的累积总和,以新玩家的累积总和开始。我使用当前查询获得的结果示例:

+--------+--------+-------+
| player | total  | cumul |
+--------+--------+-------+
| Arne   |     16 |    16 |
| Arne   |    -48 |   -32 |
| Arne   |     13 |   -19 |
| Arne   |    -17 |   -36 |
| Arne   |      7 |   -29 |
| Arne   |     41 |    12 |
| Arne   |    -30 |   -18 |
| Arne   |     -6 |   -24 |
| Arne   |     18 |    -6 |
| Bjorg  |     -5 |   -11 |
| Bjorg  |      9 |    -2 |
| Bjorg  |    -38 |   -40 |
| Bjorg  |    -12 |   -52 |
| Bjorg  |     11 |   -41 |
| Bjorg  |      3 |   -38 |
+--------+--------+-------+

它应该是什么样子:

 +--------+--------+-------+
 | speler | total  | cumul |
 +--------+--------+-------+
 | Arne   |     16 |    16 |
 | Arne   |    -48 |   -32 |
 | Arne   |     13 |   -19 |
 | Arne   |    -17 |   -36 |
 | Arne   |      7 |   -29 |
 | Arne   |     41 |    12 |
 | Arne   |    -30 |   -18 |
 | Arne   |     -6 |   -24 |
 | Arne   |     18 |    -6 |
 | Bjorg  |     -5 |    -5 |
 | Bjorg  |      9 |     4 |
 | Bjorg  |    -38 |   -34 |
 | Bjorg  |    -12 |   -46 |
 | Bjorg  |     11 |   -35 |
 | Bjorg  |      3 |   -32 |
 +--------+--------+-------+

第一个表的问题是第二个玩家使用前一个玩家的累积开始。我应该如何更改我的查询以便在玩家之间切换?

这是我的查询:

SELECT t.player,
     t.total,
     @running_total := @running_total + t.total AS cumul
FROM ( SELECT player, id, sum(punten) as total FROM `whiteboard_games` 
WHERE 1 group by player, id) t
JOIN (SELECT @running_total := 0) table1
ORDER BY t.player, id

提前致谢!

4

1 回答 1

3

试试这个查询

select 
    @score:=if(@prevPlayer = player, @score+total, total) as cumil,
    total, 
    @prevPlayer:=player as player 
from
    (select * from tbl order by player) a join 
    (select @score:=0, @prevPlayer:='') b

结果

| CUMIL | TOTAL | PLAYER |
--------------------------
|    16 |    16 |   Arne |
|    34 |    18 |   Arne |
|    28 |    -6 |   Arne |
|    -2 |   -30 |   Arne |
|    39 |    41 |   Arne |
|    46 |     7 |   Arne |
|    29 |   -17 |   Arne |
|    42 |    13 |   Arne |
|    -6 |   -48 |   Arne |
|    11 |    11 |  Bjorg |
|    -1 |   -12 |  Bjorg |
|   -39 |   -38 |  Bjorg |
|   -30 |     9 |  Bjorg |
|   -35 |    -5 |  Bjorg |
|   -32 |     3 |  Bjorg |

小提琴

于 2013-04-17T13:53:01.840 回答