All problems

What's Each Customer's Typical Order Size?

mediumSQLJoinsGroupBy

Customer success at Whetcode Supply is drawing up a list of accounts worth a personal call, and wants to separate two kinds of good customer. Some place small orders often; some place large orders rarely. A total spend figure blurs the two together, so the team has asked for the typical size of a single order instead.

That figure is not in the order log, and not because it was forgotten. An order line records a quantity and a product_id but no money at all — the price is a property of the product and is kept once, on the product row. So an order's value has to be worked out before the word "typical" means anything.

orders — one row per order line. quantity is the number of units bought; product_id points at a row in products.

id customer_id product_id quantity order_date
1 1 1 2 2023-02-01
2 1 4 1 2023-02-01
3 2 2 1 2023-02-10
4 3 3 3 2023-03-05
5 4 5 5 2023-03-11
6 1 3 1 2023-04-02
7 5 1 4 2023-05-20
8 2 5 2 2023-05-22
9 3 4 1 2023-06-01
10 5 2 1 2023-06-15

products — one row per item on sale. price is the price of a single unit, in dollars.

id name category price
1 Wireless Mouse electronics 25.0
2 Standing Desk furniture 350.0
3 Desk Lamp furniture 40.0
4 Mechanical Keyboard electronics 85.0
5 Notebook Set office 12.0

Both tables already exist in the database — there is nothing to create or load.

Task: Write a query returning two columns, customer_id and avg_order_value, with one row for every customer who has ordered, rounded to 2 decimal places. An order line is worth its quantity multiplied by that product's price, and avg_order_value is the average of those values across that customer's own order lines. A customer with no orders produces no row. Rows come back in ascending customer_id order.

Example output — shape only; the figures below are invented, not this data's answer.

customer_id avg_order_value
6 44.5
8 310
9 127.75

Sign in to solve this problem

Reading problems is free for everyone — solving them (Run, Submit, and tracking what you've solved) needs an account.

Sign in

Discussion

Sign in to join the discussion — reading is open to everyone.

Loading comments…