Return one number: the average order amount EXCLUDING the top 5 percent largest orders, rounded to 2 decimals…
SQLLevel: IntermediateAbove-average and subqueries
Return one number: the average order amount EXCLUDING the top 5 percent largest orders, rounded to 2 decimals (trimmed_avg).
Table definitions (from the source exercise):
CREATE TABLE orders(order_id INTEGER PRIMARY KEY, customer_id INTEGER, order_date TEXT, amount REAL, rep_id INTEGER, discount REAL);
Hints
- Define one output row and the source-table keys.
- Check duplicates, NULLs and the order of filtering and aggregation.
Answer
Approach: PERCENT_RANK over amount in a subquery; average the rows with pr < 0.95.
SELECT ROUND(AVG(amount), 2) AS trimmed_avg
FROM (
SELECT amount, PERCENT_RANK() OVER (ORDER BY amount) AS pr
FROM orders
) x
WHERE pr < 0.95;
The source uses SQLite with a MySQL compatibility layer. Date and string functions are dialect dependent; the query is preserved as published.
Source and licence: SQL Practice Lab — Ebrahim Sharifi · MIT