Highest-Grossing Items
Beginner Mode
Objective
Write a SQL query to find the top 2 highest-grossing products within each category for the year 2022.
Table Schema:
product_spend
| Column | Type | Description |
|---|---|---|
| transaction_id | INTEGER | Unique identifier for each transaction |
| product_id | INTEGER | ID of the product purchased |
| category | VARCHAR | Product category (e.g., Electronics, Clothing, Books) |
| product | VARCHAR | Name of the product |
| spend | DECIMAL | Amount spent on the product in this transaction |
| transaction_date | DATE | Date when the transaction occurred |
Task Requirements:
- Filter transactions for the year 2022
- Calculate total spend for each product within each category
- Identify the top 2 products by total spend in each category
- Order results by category and total spend (descending)
Output columns: category, product, total_spend
Examples
Example 1:
Output:
Input:
| product_spend | |||||
|---|---|---|---|---|---|
| category | product | product_id | spend | transaction_date | transaction_id |
| Electronics | Laptop | 101 | 1200 | 2022-01-15 | 1 |
| Electronics | Laptop | 101 | 1200 | 2022-02-20 | 2 |
| Electronics | Headphones | 102 | 150 | 2022-03-10 | 3 |
| Electronics | Mouse | 103 | 25 | 2022-04-05 | 4 |
| Clothing | Jacket | 201 | 80 | 2022-05-12 | 5 |
| Clothing | Shoes | 202 | 120 | 2022-06-18 | 6 |
| category | product | total_spend |
|---|---|---|
| Clothing | Shoes | 120 |
| Clothing | Jacket | 80 |
| Electronics | Laptop | 2400 |
| Electronics | Headphones | 150 |
Code Environment
Sign in or try as guest to run your code.
Track
| Question | Difficulty | Company | Access |
|---|
Need more practice in this area? Explore more questions →
Amazon