Bird
0
0

Given a table SurveyResults with columns RespondentID, Q1, Q2, Q3 where Q1, Q2, Q3 are answers, how can you transform this table to have columns RespondentID, Question, Answer using SQL?

hard📝 Application Q9 of 15
SQL - Advanced Query Patterns
Given a table SurveyResults with columns RespondentID, Q1, Q2, Q3 where Q1, Q2, Q3 are answers, how can you transform this table to have columns RespondentID, Question, Answer using SQL?
AUse GROUP BY RespondentID and aggregate answers.
BUse PIVOT to create columns for each answer.
CUse UNPIVOT to convert Q1, Q2, Q3 columns into Question and Answer rows.
DUse WHERE clause to filter questions.
Step-by-Step Solution
Solution:
  1. Step 1: Understand desired output

    We want to list each respondent's answers as rows with question and answer columns.
  2. Step 2: Select correct SQL operation

    UNPIVOT converts multiple columns into rows with key-value pairs, matching the goal.
  3. Final Answer:

    Use UNPIVOT to convert Q1, Q2, Q3 columns into Question and Answer rows. -> Option C
  4. Quick Check:

    UNPIVOT for column to row transformation [OK]
Quick Trick: UNPIVOT columns to key-value rows [OK]
Common Mistakes:
  • Using PIVOT wrongly
  • Trying to aggregate answers
  • Filtering instead of transforming

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More SQL Quizzes