Skip to content
Onsite

Split customers into spend quartiles

MediumP3Coding

Table orders:

ColumnType
idint (primary key)
customer_idint
amountint

Add up each customer's orders, then split customers into 4 groups of (nearly) equal size by total spend: quartile 1 holds the lowest spenders and quartile 4 the highest. When the customer count does not divide by 4, the first groups get the extra customers. Customers with equal totals are ordered by customer_id.

Output columns: customer_id, total, quartile.

Schema

CREATE TABLE orders (
  id int PRIMARY KEY,
  customer_id int NOT NULL,
  amount int NOT NULL
);

Example 1

Input
8 customers with totals 10, 20, ..., 80
Output
customers 1 and 2 are in quartile 1, 3 and 4 in 2, 5 and 6 in 3, 7 and 8 in 4

Constraints

  • PostgreSQL dialect.

Hints

PostgreSQL
Run checks the 3 visible tests, Submit all 7.