Top-N per Group Query in SQL
📖 Scenario: You are managing a sales database for a retail company. The company wants to identify the top 2 best-selling products in each category based on the total sales amount.
🎯 Goal: Write an SQL query to find the top 2 products with the highest sales amount in each product category.
📋 What You'll Learn
Create a table called
sales with columns category, product, and sales_amount.Insert the given sales data into the
sales table.Write a query using window functions to rank products by sales amount within each category.
Select only the top 2 products per category based on the ranking.
💡 Why This Matters
🌍 Real World
Retail companies often need to find top-selling products in each category to focus marketing and inventory efforts.
💼 Career
Knowing how to write top-N per group queries is essential for data analysts and database developers working with sales or transactional data.
Progress0 / 4 steps