Intento hacer una tabla pivote en MySQL utilizando como base la siguiente tabla llamada "lab_user_scores":
+------------+------------+---------+-------+ | id_problem | subproblem | id_user | score | +------------+------------+---------+-------+ | 1 | 1 | Bob | 15 | | 1 | 2 | Bob | 20 | | 2 | 1 | Bob | 40 | | 2 | 2 | Bob | 25 | | 1 | 1 | Alice | 5 | +------------+------------+---------+-------+
Mi idea es tener una tabla como la siguiente:
+---------+--------+--------+--------+--------+-------------+ | id_user | (1, 1) | (1, 2) | (2, 1) | (2, 2) | total_score | +---------+--------+--------+--------+--------+-------------+ | Alice | 15 | 20 | 40 | 25 | 100 | | Bob | 5 | 0 | 0 | 0 | 5 | +---------+--------+--------+--------+--------+-------------+
Tengo el siguiente código en SQL:
SELECT
id_user,
CASE WHEN id_problem = 1 AND subproblem = 1 THEN score ELSE 0 END AS "(1, 1)",
CASE WHEN id_problem = 1 AND subproblem = 2 THEN score ELSE 0 END AS "(1, 2)",
CASE WHEN id_problem = 2 AND subproblem = 1 THEN score ELSE 0 END AS "(2, 1)",
CASE WHEN id_problem = 2 AND subproblem = 2 THEN score ELSE 0 END AS "(2, 2)",
SUM(score) AS total_score
FROM lab_user_scores GROUP BY id_user
Ejecutando la sentencia anterior, obtengo el siguiente resultado:
+----------+--------+--------+--------+--------+-------------+ | id_user | (1, 1) | (1, 2) | (2, 1) | (2, 2) | total_score | +----------+--------+--------+--------+--------+-------------+ | Alice | 15 | 0 | 0 | 0 | 100 | | Bob | 5 | 0 | 0 | 0 | 5 | +----------+--------+--------+--------+--------+-------------+
Agradecería si alguien pudiera proveerme alguna orientación, de antemano, ¡gracias!
sum(CASE WHEN id_problem = 2 AND subproblem = 2 THEN score ELSE 0 END) AS "(2, 2)"
SUM