Challenge - 5 Problems
Pivot and Unpivot Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Output of a simple PIVOT query
Given the table Sales with columns
Year, Product, and Amount, what is the output of this PIVOT query?SELECT * FROM ( SELECT Year, Product, Amount FROM Sales ) AS SourceTable PIVOT ( SUM(Amount) FOR Product IN ([A], [B]) ) AS PivotTable ORDER BY Year;
SQL
CREATE TABLE Sales (Year INT, Product VARCHAR(10), Amount INT); INSERT INTO Sales VALUES (2020, 'A', 100), (2020, 'B', 150), (2021, 'A', 200), (2021, 'B', 250);
Attempts:
2 left
💡 Hint
Remember that PIVOT aggregates values and arranges them as columns based on the specified IN list.
✗ Incorrect
The PIVOT query sums Amounts for each Product per Year, turning Product values into columns A and B with their sums.
❓ query_result
intermediate2:00remaining
Output of an UNPIVOT query
Given the table MonthlySales with columns
Year, Jan, Feb, what is the output of this UNPIVOT query?SELECT Year, Month, Sales FROM MonthlySales UNPIVOT ( Sales FOR Month IN (Jan, Feb) ) AS UnpivotTable ORDER BY Year, Month;
SQL
CREATE TABLE MonthlySales (Year INT, Jan INT, Feb INT); INSERT INTO MonthlySales VALUES (2020, 100, 150), (2021, 200, 250);
Attempts:
2 left
💡 Hint
UNPIVOT converts columns into rows, so each month becomes a row with its sales.
✗ Incorrect
The UNPIVOT query transforms the Jan and Feb columns into rows under Month with corresponding Sales values.
🧠 Conceptual
advanced1:30remaining
Understanding PIVOT aggregation behavior
Why does a PIVOT operation in SQL require an aggregation function like SUM or COUNT?
Attempts:
2 left
💡 Hint
Think about what happens when multiple rows share the same pivot column value.
✗ Incorrect
PIVOT groups rows by the pivot column and aggregates values to produce one row per group with summarized columns.
📝 Syntax
advanced1:30remaining
Identify the syntax error in this PIVOT query
Which option contains a syntax error in this PIVOT query?
SELECT * FROM ( SELECT Year, Product, Amount FROM Sales ) AS SourceTable PIVOT ( SUM(Amount) FOR Product IN (A, B) ) AS PivotTable;
Attempts:
2 left
💡 Hint
Check the syntax for the IN list in PIVOT clause.
✗ Incorrect
In SQL Server PIVOT, the IN list must use square brackets around column names to be valid identifiers.
❓ optimization
expert3:00remaining
Optimizing UNPIVOT for large datasets
You have a large table with many monthly sales columns (Jan to Dec). Which approach optimizes performance when unpivoting these columns into rows?
Attempts:
2 left
💡 Hint
Consider SQL Server's CROSS APPLY with VALUES for better performance than UNPIVOT.
✗ Incorrect
CROSS APPLY with VALUES is often faster and more flexible than UNPIVOT for large wide tables.