All problems

Orders Above the Average

hardSQLSubqueriesJoins

Fraud review at Whetcode Supply cannot look at every order, so it samples: anything worth more than a typical order gets a human glance, on the reasoning that a stolen card is used for something expensive rather than for a notebook set.

The cut-off is not a number anyone can type. It is the average order value, computed from the same orders being filtered, and it moves with every sale. Writing today's figure into the query gives a rule that is wrong next week and never says so.

orders — one row per order. customer_id is the id of the customer who placed it, product_id the id of the item bought, quantity how many units of that item, and order_date the day it was placed. An order row covers one item only.

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 — the catalogue, one row per item on sale. price is what a single unit costs, 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

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

Task: Write a query returning two columns, id (the order's own id) and order_value (that order's item price times its number of units, rounded to two decimal places), one row per order worth strictly more than the average order value across all orders — equal to the average does not qualify. Rows come back by order_value, largest first; two orders here are worth exactly the same, so break that tie on id, smallest first. The review queue must read the same way every time it is built.

Example output

id order_value
7 500
2 85

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…