Skip to content

Median dining spend by month, without percentile functions

HardFull bankMedians and percentilesRanking and top N20 min2 hidden datasets

The task

A reporting tool in your company only supports plain SQL: no percentile_cont, no percentile_disc. Compute the median with window functions and ordinary arithmetic instead.

A dining purchase is a transaction with category = 'dining' and a negative amount. Its size is the positive value -amount. Group dining purchases by the calendar month of posted_at.

For each month with at least one dining purchase, return month (the first day of the month), purchases (how many) and median_size, the median purchase size rounded to 2 decimal places. When a month has an even number of purchases, the median is the average of the two middle sizes. Equal sizes are separate purchases and each counts once.

Sort by month.

Expected output

monthpurchasesmedian_size
  • Sorted by month ascending.
  • Numbers rounded to 2 decimal places.
  • 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