Created
January 8, 2026 07:57
-
-
Save paigeadelethompson/94d8ff1e7c6d85dee90406cbdcfc8454 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| WITH CategorySales AS ( | |
| -- 1. Calculate total sales for each product within its category | |
| SELECT | |
| p.ProductID, | |
| p.ProductName, | |
| c.CategoryName, | |
| SUM(od.Quantity * od.UnitPrice) AS TotalSales, | |
| -- 2. Use a window function to rank products within each category | |
| ROW_NUMBER() OVER ( | |
| PARTITION BY c.CategoryID | |
| ORDER BY SUM(od.Quantity * od.UnitPrice) DESC | |
| ) AS Rank | |
| FROM | |
| Products p | |
| JOIN | |
| Categories c ON p.CategoryID = c.CategoryID | |
| JOIN | |
| OrderDetails od ON p.ProductID = od.ProductID | |
| GROUP BY | |
| p.ProductID, p.ProductName, c.CategoryID, c.CategoryName | |
| ) | |
| -- 3. Select the top 3 products from the CTE result | |
| SELECT | |
| CategoryName, | |
| ProductName, | |
| TotalSales | |
| FROM | |
| CategorySales | |
| WHERE | |
| Rank <= 3 | |
| ORDER BY | |
| CategoryName, Rank; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment