Bird
0
0

Which SQL approach correctly unpivots this data?

hard📝 Application Q15 of 15
SQL - Advanced Query Patterns
You have a table MonthlySales with columns Store, Jan, Feb, Mar representing sales per month. You want to create a report listing Store, Month, Sales rows. Which SQL approach correctly unpivots this data?
AUse UNPIVOT: <code>SELECT Store, Month, Sales FROM MonthlySales UNPIVOT (Sales FOR Month IN ([Jan], [Feb], [Mar])) AS Unpvt;</code>
BUse PIVOT: <code>SELECT Store, Month, Sales FROM MonthlySales PIVOT (SUM(Sales) FOR Month IN ([Jan], [Feb], [Mar])) AS Pvt;</code>
CUse JOIN to combine Jan, Feb, Mar columns into rows
DUse GROUP BY Store, Month without unpivot
Step-by-Step Solution
Solution:
  1. Step 1: Identify the goal

    We want to transform columns Jan, Feb, Mar into rows with Month and Sales columns.
  2. Step 2: Choose correct SQL operation

    UNPIVOT converts columns into rows; Use UNPIVOT: SELECT Store, Month, Sales FROM MonthlySales UNPIVOT (Sales FOR Month IN ([Jan], [Feb], [Mar])) AS Unpvt; uses correct syntax for this.
  3. Step 3: Evaluate other options

    PIVOT aggregates rows into columns (wrong direction), JOIN is complex and unnecessary, GROUP BY alone doesn't reshape columns.
  4. Final Answer:

    Use UNPIVOT: SELECT Store, Month, Sales FROM MonthlySales UNPIVOT (Sales FOR Month IN ([Jan], [Feb], [Mar])) AS Unpvt; -> Option A
  5. Quick Check:

    Unpivot columns to rows = Use UNPIVOT: SELECT Store, Month, Sales FROM MonthlySales UNPIVOT (Sales FOR Month IN ([Jan], [Feb], [Mar])) AS Unpvt; [OK]
Quick Trick: Unpivot columns to rows using UNPIVOT with FOR and IN [OK]
Common Mistakes:
  • Using PIVOT instead of UNPIVOT
  • Trying to reshape with GROUP BY only
  • Overcomplicating with JOINs

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More SQL Quizzes