Hvis du kun har to værdier for item_id
, så er det fint at hårdkode værdier. Eksempel
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
Ellers, når du har ukendt antal scores, en Dynamic SQL
er meget foretrukket.
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;
Begge forespørgsler vil OUTPUT det samme
╔══════════════╦══════════════╦══════════════╗
║ STUDENT_NAME ║ ITEM_1_SCORE ║ ITEM_2_SCORE ║
╠══════════════╬══════════════╬══════════════╣
║ dan ║ 55 ║ 44 ║
║ david ║ 66 ║ 45 ║
║ jon ║ 37 ║ 45 ║
╚══════════════╩══════════════╩══════════════╝