24. Share of Category Total
Difficulty: Medium · Topics: Window Functions
For each product in sales, compute pct_of_category: its amount as a percentage of its category's total, rounded to 1 decimal.
Return category, product, amount, pct_of_category, keeping every row (no collapsing).
Row order does not matter; column names must match. Your code is graded on 3 test cases, including hidden edge cases.
Sample data
sales
| category | product | amount |
|---|---|---|
| fruit | apple | 30 |
| fruit | banana | 10 |
| fruit | cherry | 60 |
| veg | kale | 25 |
| veg | leek | 75 |
Expected output
| category | product | amount | pct_of_category |
|---|---|---|---|
| fruit | apple | 30 | 30 |
| fruit | banana | 10 | 10 |
| fruit | cherry | 60 | 60 |
| veg | kale | 25 | 25 |
| veg | leek | 75 | 75 |
Hints
Hint 1
A window partitioned by category with no ordering sees the whole partition.Hint 2
F.sum("amount").over(Window.partitionBy("category")) is the category total on every row.Hint 3
Divide, multiply by 100, round to 1 decimal.PySpark functions you'll practise
- Window spec
- sum
Related problems
- Running Total by Region · Medium · Window Functions
- Trailing 3 Calendar Days (Range Frame) · Hard · Window Functions
- Sessionize a Clickstream · Hard · Window Functions
- Latest Order per Customer · Medium · Window Functions
- Top Two Salary Levels per Department · Medium · Window Functions
Browse
Topics: Window Functions · Joins · Aggregations · Pivot, Unpivot & Rollup · Arrays · Null Handling · Conditional Logic · Dates · Filtering & Selection · Strings
Difficulty: Easy · Medium · Hard · PySpark interview roadmap · All problems