Si solo tiene dos valores para item_id
, entonces está bien codificar valores. Ejemplo
SELECT a.Name AS Student_Name,
MAX(CASE WHEN item_id = '01' THEN b.score END) Item_1_Score,
MAX(CASE WHEN item_id = '02' THEN b.score END) Item_2_Score
FROM student_info a
LEFT JOIN scores b
ON a.id = b.student_ID
GROUP BY a.Name
De lo contrario, cuando tenga un número desconocido de puntajes, un Dynamic SQL
es mucho más preferido.
SELECT GROUP_CONCAT(DISTINCT
CONCAT('MAX(CASE WHEN item_id = ''',
item_id,
''' THEN Score END) AS ',
CONCAT('`Item_', item_id, '_Score`')
)) INTO @sql
FROM scores;
SET @sql = CONCAT('SELECT a.Name AS Student_Name, ', @sql, '
FROM student_info a
LEFT JOIN scores b
ON a.id = b.student_ID
GROUP BY a.Name');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Ambas consultas RESULTARAN lo mismo
╔══════════════╦══════════════╦══════════════╗
║ STUDENT_NAME ║ ITEM_1_SCORE ║ ITEM_2_SCORE ║
╠══════════════╬══════════════╬══════════════╣
║ dan ║ 55 ║ 44 ║
║ david ║ 66 ║ 45 ║
║ jon ║ 37 ║ 45 ║
╚══════════════╩══════════════╩══════════════╝