Each row of Sales is one sale.
Find the top 3 categories by total revenue for sales with sale_date >= '2024-01-01' and sale_date < '2024-01-31'. Return each category and its total revenue, ordered by total revenue descending, then category name ascending. Return only the top 3 rows.
Input Table(s)
Sales (primary key sale_id)
| Column | Type | Meaning |
|---|
sale_id | INT | Sale identifier, primary key |
category | VARCHAR(100) | Product category; NOT NULL and non-empty |
revenue | DECIMAL(12,2) | Revenue from the sale; NOT NULL and positive |
sale_date | DATE | Day of the sale; NOT NULL |
Output Contract
-
Columns, in this order:
category
,
total_revenue
.
-
total_revenue
is the sum of
revenue
over the category's sales inside the window, at its natural scale of 2 decimal places with no extra rounding.
-
Order by
total_revenue
descending, then
category
ascending. Each row is a different category, so the order is unique.
-
Return at most 3 rows. When categories tie on total revenue at the cut, the category-name order decides which ones make the top 3.
Example
Sales
| sale_id | category | revenue | sale_date |
|---|
| 1 | Books | 120.00 | 2024-01-03 |
| 2 | Electronics | 450.00 | 2024-01-10 |
| 3 | Books | 80.00 | 2024-01-15 |
| 4 | Garden | 200.00 | 2024-01-20 |
| 5 | Toys | 200.00 | 2024-01-22 |
| 6 | Toys | 500.00 | 2024-01-31 |
| 7 | Electronics | 50.00 | 2023-12-31 |
| 8 | Apparel | 150.00 | 2024-01-05 |
Expected result:
| category | total_revenue |
|---|
| Electronics | 450.00 |
| Books | 200.00 |
| Garden | 200.00 |
Sale 7 falls before the window, and sale 6 falls on January 31, which the strict upper bound excludes. That leaves Electronics at 450.00, Books, Garden and Toys tied at 200.00, and Apparel at 150.00. Name order keeps Books and Garden ahead of Toys.
Constraints and Clarifications
-
Sales
has at most 10,000 rows.
-
The window covers 2024-01-01 through 2024-01-30 inclusive. Sales dated 2024-01-31 are outside it.
-
Categories with no sales in the window do not appear. If fewer than 3 categories have sales in the window, return all of them.
-
No column contains NULL and
sale_id
is unique, so there are no NULLs or repeated rows to handle. A category with several sales on one day sums all of them.