Use uncorrelated subqueries in WHERE and SELECT clauses
I want to identify our above-average performers. Pull every active Sales department employee whose total revenue exceeds the average total revenue across all active Sales reps. Show their name, their total revenue, and the department average for context. Sort by revenue descending.
| Column | Type | Key |
|---|---|---|
| sale_id | INT | PK |
| employee_id | INT | FK → dim_employees |
| product_id | INT | FK → dim_products |
| region_id | INT | FK → dim_regions |
| sale_date | TEXT | |
| quantity | INT | |
| revenue | REAL | |
| discount | REAL |
| Column | Type | Key |
|---|---|---|
| employee_id | INT | PK |
| first_name | TEXT | |
| last_name | TEXT | |
| TEXT | ||
| department | TEXT | |
| title | TEXT | |
| hire_date | TEXT | |
| salary | INT | |
| manager_id | INT | |
| is_active | INT |
Each hint you reveal reduces the XP you can earn. Try the query first.
This is a two-step problem: first compute each rep's total revenue, then compare each rep to the average across all reps. Think about how to express "the average of per-rep totals" in SQL.
The department average is the average of per-rep totals — use a subquery: SELECT AVG(rep_total) FROM (SELECT SUM(revenue) as rep_total ...)
Compare each rep's total to this average in a HAVING clause or wrap the whole thing in a subquery