Skip to content

Months each merchant ranked in the top three for spend

MediumFull bankRanking and top NGroup and aggregateDates and time16 min3 hidden datasets

The task

The cards team tracks which merchants dominate everyday spending. A transaction counts as everyday spending when its category is dining, groceries or travel. A merchant's spend in a calendar month is the sum of -amount over its everyday transactions posted in that month (month of posted_at). Rent, refunds, fees, salary and transfers are ignored.

For each month, rank merchants by spend, highest first. Merchants with the same spend share a rank, and the next rank skips ahead (1, 1, 3). A merchant is in the top three of a month when its rank is 3 or better, so ties at the cut-off are all included.

Return merchant and months_in_top_three, the number of months in which the merchant was in the top three. Merchants that were never in the top three do not appear. Sort by months_in_top_three descending, then merchant ascending.

Expected output

merchantmonths_in_top_three
  • Sorted by months_in_top_three descending, then merchant ascending.
  • Checked on the sample and on 3 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