Bird
0
0

How can you modify this query to get the top 3 salespeople per region based on total sales?

hard📝 Application Q9 of 15
SQL - Advanced Query Patterns
How can you modify this query to get the top 3 salespeople per region based on total sales?

SELECT region, salesperson, SUM(amount) AS total_sales FROM sales GROUP BY region, salesperson;
AAdd WHERE total_sales <= 3
BWrap it in a subquery and use ROW_NUMBER() OVER (PARTITION BY region ORDER BY total_sales DESC) to filter top 3
CUse HAVING COUNT(*) <= 3
DAdd ORDER BY total_sales DESC LIMIT 3
Step-by-Step Solution
Solution:
  1. Step 1: Aggregate sales per salesperson per region

    The original query groups sales per salesperson and region.
  2. Step 2: Use ROW_NUMBER() in subquery to rank salespeople per region

    Wrap the aggregation in a subquery, then assign row numbers partitioned by region ordered by total_sales descending.
  3. Step 3: Filter top 3 per region

    Filter rows where row number <= 3 to get top 3 salespeople per region.
  4. Final Answer:

    Wrap it in a subquery and use ROW_NUMBER() OVER (PARTITION BY region ORDER BY total_sales DESC) to filter top 3 -> Option B
  5. Quick Check:

    Use subquery with ROW_NUMBER() after aggregation [OK]
Quick Trick: Aggregate first, then rank with ROW_NUMBER() in subquery [OK]
Common Mistakes:
  • Filtering on aggregate in WHERE instead of HAVING or subquery
  • Using LIMIT without partitioning
  • Misusing HAVING with COUNT for top N

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More SQL Quizzes