Skip to content

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

categoryproductamount
fruitapple30
fruitbanana10
fruitcherry60
vegkale25
vegleek75

Expected output

categoryproductamountpct_of_category
fruitapple3030
fruitbanana1010
fruitcherry6060
vegkale2525
vegleek7575

Hints

Hint 1A window partitioned by category with no ordering sees the whole partition.
Hint 2F.sum("amount").over(Window.partitionBy("category")) is the category total on every row.
Hint 3Divide, multiply by 100, round to 1 decimal.

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

Difficulty: Easy · Medium · Hard · PySpark interview roadmap · All problems