Skip to content

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

productquarterrevenue
AQ1100
AQ150
AQ2200
BQ370
BQ430
AQ410

Expected output

productQ1Q2Q3Q4
A150200null10
Bnullnull7030

Hints

Hint 1groupBy("product").pivot("quarter") turns distinct quarter values into columns.
Hint 2Pass the values explicitly — pivot("quarter", ["Q1","Q2","Q3","Q4"]) — so Spark skips an extra job and a missing quarter still gets a column.
Hint 3Finish with .sum("revenue").

Learn the concepts

PySpark functions you'll practise

Related problems

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