चूंकि आप 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;
# 1 संपादित करें, यदि आपके events
एक अलग तालिका में संग्रहीत हैं, तो आप गतिशील परिणाम उत्पन्न करने के लिए निम्नलिखित का उपयोग कर सकते हैं:
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 with Demo