I have a table of matches where I want to obtain the sum of the points of the players, the player is crossed with the player table where the id is the identifier, in the game table the player can appear in both player_a and player_b, that is, when I do the sum of the points of the players I look for the id of the player in the two columns. I get stuck a bit with the query and I can't solve it, it adds the points only when the id corresponds to player_a, but it doesn't add when the points correspond to the id of player_b.
SELECT
(puntos_a + puntos_b) AS puntos,
id
FROM
(
SELECT
SUM(puntos_jugador_a) AS puntos_a,
0 AS puntos_b,
jugador_a AS id
FROM
game
WHERE
torneo_organizacion = "MZF-CAB"
GROUP BY
jugador_a
UNION ALL
SELECT
0 AS puntos_a,
SUM(puntos_jugador_b) AS puntos_b,
jugador_b AS id
FROM
game
WHERE
torneo_organizacion = "MZF-CAB"
GROUP BY
jugador_b
) t
GROUP BY
id
I think the simplest is to do it as follows:
I have divided the query into two: get the list of players and get the sum of the points.
To begin with, I obtain the complete list of players through the following query:
Later, with that list of players, we can obtain the sum of points in a similar way as I indicated before:
Add the points of
puntos_jugador_a
if this isjugador_a
or, if not, add the points ofpuntos_jugador_b
.You can see the query work online at the following link: