Skip to content

Orders above the customer's own average order

MediumFull bankCTEs and subqueriesGroup and aggregate14 min2 hidden datasets

The task

The retention team wants to spot big-ticket moments for each customer: orders that are larger than that customer's usual order.

  • Only orders with status = 'completed' are considered, both for the list and for the averages.
  • An order's order_value is the sum of quantity * unit_price over its items. Shipping is not included. A completed order with no items has an order_value of 0 and still counts in the average.
  • A customer's customer_avg is the average order_value over their completed orders.

Return every completed order whose order_value is strictly greater than its customer's customer_avg. Give order_id, customer_id, order_value and customer_avg (rounded to 2 decimal places), sorted by order_id. Customers with a single completed order never qualify.

Expected output

order_idcustomer_idorder_valuecustomer_avg
  • Sorted by order_id ascending.
  • Numbers rounded to 2 decimal places.
  • Checked on the sample and on 2 hidden datasets. How grading works

Tables Online store · click a name to insert it

customers150 rows in the sample

One row per customer account. Key: customer_id.

intUnique id.
textName on the account.
textNULL when the customer never gave one (marketplace buyers).
textTwo-letter country code.
dateDay the account was created.
textorganic, paid_search, social, referral or email. NULL when unknown.
products36 rows in the sample

The catalog. Key: product_id.

intUnique id.
textDisplay name.
textKitchen, Home, Outdoors, Books, Beauty or Toys.
numeric(10,2)Current list price in USD.
dateFirst day on sale.
orders700 rows in the sample

One row per order. Key: order_id.

intUnique id.
intWho placed it.
timestampWhen it was placed (UTC).
textcompleted, cancelled or refunded.
textweb, app or marketplace.
numeric(10,2)Shipping charged, USD.
textCoupon used, NULL if none.
order_items1,266 rows in the sample

One row per product in an order. Key: order_id, product_id.

intThe order.
intThe product.
intUnits bought.
numeric(10,2)Price paid per unit, after discounts, USD.
returns79 rows in the sample

Items sent back. Key: return_id.

intUnique id.
intThe original order.
intThe product returned.
dateDay the return arrived.
intUnits returned.
textdamaged, wrong_item, not_as_described or changed_mind. NULL when not given.

Related questions

Loading the editor and PostgreSQL