The Question
SQLTop Product per Category with Tie-breaking
Given a 'products' table (product_id, product_name, category_name) and a transactional 'product_sales' table (product_id, sales_quantity, rating), identify the best-selling product within each category. The 'best-selling' product is defined as having the highest aggregate sales quantity. In the event of a tie in sales volume, the product with the higher average rating should be selected. If a tie still exists after considering both metrics, return all such tied products. The final output must include the category name and product name, sorted alphabetically by category name.
PostgreSQL
Window Func
CTE
Inner Join
Aggregate Func
March 16, 2026