54. Pivot Quarterly Revenue
Difficulty: Medium · Topics: Pivot, Unpivot & Rollup, Aggregations
sales has one row per sale: product, quarter, revenue where quarter is one of Q1–Q4.
Return one row per product with the columns product, Q1, Q2, Q3, Q4 holding the total revenue in each quarter. A quarter with no sales must be null.
Row order does not matter; column names must match. Your code is graded on 3 test cases, including hidden edge cases.
Sample data
sales
| product | quarter | revenue |
|---|---|---|
| A | Q1 | 100 |
| A | Q1 | 50 |
| A | Q2 | 200 |
| B | Q3 | 70 |
| B | Q4 | 30 |
| A | Q4 | 10 |
Expected output
| product | Q1 | Q2 | Q3 | Q4 |
|---|---|---|---|---|
| A | 150 | 200 | null | 10 |
| B | null | null | 70 | 30 |
Hints
Hint 1
groupBy("product").pivot("quarter") turns distinct quarter values into columns.Hint 2
Pass the values explicitly —pivot("quarter", ["Q1","Q2","Q3","Q4"]) — so Spark skips an extra job and a missing quarter still gets a column.Hint 3
Finish with.sum("revenue").Learn the concepts
- pivot · 5 min read. Turn row values into columns, and why passing the values list up front makes it faster.
- groupBy + agg · 4 min read. Aggregate rows per group: counts, sums, averages, and how count(*) differs from count(col).
PySpark functions you'll practise
- groupBy
- sum
- pivot
Related problems
- Survey Scores by Question · Medium · Pivot, Unpivot & Rollup, Aggregations
- Unpivot Wide Columns to Rows · Medium · Pivot, Unpivot & Rollup, Null Handling, Filtering & Selection
- Pivot with Several Aggregations · Hard · Pivot, Unpivot & Rollup, Aggregations, Null Handling
- Subtotals with ROLLUP · Hard · Pivot, Unpivot & Rollup, Aggregations, Conditional Logic, Filtering & Selection
- All Combinations with CUBE · Hard · Pivot, Unpivot & Rollup, Aggregations, Conditional Logic
Browse
Topics: Window Functions · Joins · Aggregations · Pivot, Unpivot & Rollup · Arrays · Null Handling · Conditional Logic · Dates · Filtering & Selection · Strings · Data Lake · Lakehouse · Streaming · Data Prep for AI · Spark Performance
Difficulty: Easy · Medium · Hard · Learn · All problems · dbt practice