My SQL: Sum each row After Specific Row

时间:2017-01-19 15:24:08

标签: mysql

I have a table which collects the results of football games played every week.

Based on the results of each game I input 3, 1 or 0 points for a player by ID, depending one whether they have won, drawn, or lost.

id  Name    A1  B1  C1  A2  B2  C2

1   C       0   3   1   3   0   0

2   G       3   0   1   3   0   0

3   k       3   0   1   0   3   3

4   S       3   0   1   N   N   N

5   G       N   N   N   3   0   0

6   D       N   N   N   N   N   N

I'd like to be able to sum these columns, and I can do it manually by using SELECT SUM(A1+B1+C1+A2+B2+C2) FROM Results WHERE id ='1'

My issue is that each week I add an additional 2 or 3 game results - so I'd need to manually add the new games into SUM().

I thought that I would be able to use something like SUM(...) AFTER Name WHERE id = 'id'

I'm hoping I can concatenate the names of all Columns after Name and then add that into SUM(concatenatedcolumns).

But I haven't found a good example to work from yet.

1 个答案:

答案 0 :(得分:0)

如果您不关心“游戏”元数据,则可以有两个表格,我假设您没有准备将游戏列为列。

table:players (rows unique by id)
id name
1  A
2  B

table:scores (rows unique by combination of game_id and player_id)
game_id, player_id, score
A1       1          3
A1       2          1
B1       1          0

然后,您可以加入这两个表格,以获得所有游戏中每位玩家的得分总和

select players.id, players.name, sum(scores.score) from players inner join score
on players.id = scores.player_id group by players.id, players.name

在“得分”表中没有出现在游戏中的玩家将不会有任何行,因此您不必处理任何空值。