MYSQL由玩家累积的总和

时间:2013-04-17 13:42:25

标签: mysql

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

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

第一个表的问题是第二个玩家使用前一个玩家的cumul开始。我应该如何改变我的查询才能在玩家之间切换?

这是我的疑问:

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

提前感谢!

1 个答案:

答案 0 :(得分: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 |

FIDDLE