MySQLを使用しているため、データを列にピボットするには、CASE
で集計関数を使用する必要があります。 式:
SELECT callSign,
SUM(case when event = 'Bridge' then score else 0 end) as Bridge,
SUM(case when event = 'PSA' then score else 0 end) as PSA,
SUM(case when event = 'Amazing Race Planning' then score else 0 end) As AmazingRacePlanning,
SUM(case when event = 'Team Analyst Exam' then score else 0 end) as TeamAnalystExam
FROM scores
LEFT JOIN candidates
ON scores.candidateID=candidates.id
WHERE candidateID IN (SELECT id
FROM candidates
WHERE assessmentID='1321')
GROUP BY callSign
events
の数が不明な場合 、次に、準備されたステートメントを使用して動的SQLを生成する必要があります。
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'sum(CASE WHEN event = ''',
event,
''' THEN score END) AS `',
event, '`'
)
) INTO @sql
FROM scores
LEFT JOIN candidates
ON scores.candidateID=candidates.id;
SET @sql
= CONCAT('SELECT callSign, ', @sql, '
FROM scores
LEFT JOIN candidates
ON scores.candidateID=candidates.id
WHERE candidateID IN (SELECT id
FROM candidates
WHERE assessmentID=''1321'')
GROUP BY callSign');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
events
の場合は#1を編集します が別のテーブルに保存されている場合は、以下を使用して動的な結果を生成できます。
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'sum(CASE WHEN event = ''',
event,
''' THEN score END) AS `',
event, '`'
)
) INTO @sql
FROM events;
SET @sql
= CONCAT('SELECT callSign, ', @sql, '
FROM scores
LEFT JOIN candidates
ON scores.candidateID=candidates.id
WHERE candidateID IN (SELECT id
FROM candidates
WHERE assessmentID=''1321'')
GROUP BY callSign');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SQL Fiddle withDemo を参照してください。