Skip to content

Favourite spending category per customer, counted by segment

HardFull bankRanking and top NGroup and aggregateJoins22 min2 hidden datasets

The task

The marketing team wants to know which spending habit dominates each customer segment. A customer's favourite category is the one in which they spent the most money in total, across all of their accounts. Only the categories dining, groceries and travel are considered, and spend is the sum of -amount over negative transactions in them.

If a customer spent exactly the same in two categories at the top, the category that comes first alphabetically is their favourite. Customers with no spend in these categories are ignored.

Return segment (from customers), favourite_category and customers (how many customers in that segment have that favourite). Only combinations that occur are returned. Sort by segment ascending, then customers descending, then favourite_category ascending.

Expected output

segmentfavourite_categorycustomers
  • Sorted by segment ascending, then customers descending, then favourite_category ascending.
  • Checked on the sample and on 2 hidden datasets. How grading works

Tables Digital bank · click a name to insert it

customers70 rows in the sample

One row per customer. Key: customer_id.

intUnique id.
textName.
dateDay they became a customer.
textretail, premium or business.
accounts126 rows in the sample

One row per account. A customer can have several. Key: account_id.

intUnique id.
intOwner.
textchecking, savings or credit.
dateOpening day.
dateClosing day. NULL while open.
transactions9,906 rows in the sample

One row per posted transaction. Positive amounts are money in, negative are money out. Key: txn_id.

bigintUnique id.
intThe account.
timestampWhen it posted (UTC).
numeric(12,2)Signed amount, USD.
textsalary, rent, groceries, dining, travel, transfer, fees or refund.
textMerchant name. NULL for salary, transfers and fees.

Related questions

Loading the editor and PostgreSQL