Fetching the top N records from each category typically requires multiple queries or complex subqueries. However, SQL window functions make it trivial. The trick is to use PARTITION BY to divide rows into groups, ORDER BY within each partition, and a ranking function like RANK() or ROW_NUMBER(). Then filter on the rank value to keep only the top N rows per group.
For example, to get the top two products by sales in each category:
SELECT product_id, category, sales
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY category ORDER BY sales DESC) AS rn
FROM products
) AS ranked
WHERE rn <= 2;
This approach is cleaner, faster, and works across all major databases. Window functions are a powerful tool every data analyst should master.