Chapter 8 · Window Functions
46. NTILE Customer Segmentation
Segment customers into 4 tiers based on their total account balance using NTILE. Tier 1 is the top 25% by balance, tier 4 is the bottom 25%. Return first_name, last_name, total_balance, tier, and the count of customers in each tier (tier_size). Use a CTE for the tier assignment and a window function for tier_size. Customers with no accounts have a balance of 0; break balance ties by customer id (lower id first). Order by tier ascending, total_balance descending.
Tables
- PKidINT
- first_nameTEXT
- last_nameTEXT
- emailTEXT
- phoneTEXT
- date_of_birthTEXT
- cityTEXT
- stateTEXT
- countryTEXT
- created_atTIMESTAMP
- PKidINT
- FKcustomer_id→ customers.idINT
- account_typeTEXT
- balanceREAL
- currencyTEXT
- opened_atTEXT
- statusTEXT
Need help?
Ask Sol
AI tutor — looks at your current query and nudges you, without spoiling the answer.
Solution
Try the hints first — solving it yourself is what makes it stick.