Skip to content

25. Customer Spend Quartiles (NTILE)

Difficulty: Medium · Topics: Window Functions

Marketing wants to split customers into four equal-sized groups by total_spend, highest spenders in quartile 1.

Return customer_id, total_spend and quartile. Break ties in spend by the smaller customer_id first. When the count does not divide evenly, the first quartiles get one extra customer.

Row order does not matter; column names must match. Your code is graded on 3 test cases, including hidden edge cases.

Sample data

customers

customer_idtotal_spend
1500
2300
3900
4100
5700
6200
7800
8400

Expected output

customer_idtotal_spendquartile
15002
23003
39001
41004
57002
62004
78001
84003

Hints

Hint 1F.ntile(4) over a window ordered by spend descending.
Hint 2Add customer_id as a second ordering key so ties are deterministic.
Hint 3ntile hands out remainder rows to the lowest bucket numbers first.

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