SQL
Lab
Amazon Easy Ranking Spend

Highest
Grossing
Items

Identify the top two highest-grossing products within each category in 2022.

Table Schema

Inspect
Table

interactive
ColumnTypeDescription
categorystringProduct category.
productstringProduct name.
user_idintegerCustomer identifier.
spenddecimalTransaction spend amount.
transaction_datetimestampTimestamp of the transaction.

Sample Data

Input
Output

Sample Input: product_spend
categoryproductuser_idspendtransaction_date
appliancerefrigerator165246.0012/26/2021 12:00:00
appliancerefrigerator123299.9903/02/2022 12:00:00
appliancewashing machine123219.8003/02/2022 12:00:00
electronicsvacuum178152.0004/05/2022 12:00:00
electronicswireless headset156249.9007/08/2022 12:00:00
electronicsvacuum145189.0007/15/2022 12:00:00
Expected Output
categoryproducttotal_spend
appliancerefrigerator299.99
appliancewashing machine219.80
electronicsvacuum341.00
electronicswireless headset249.90

SQL Editor

Run
Query

postgresql
Waiting for query

categoryproducttotal_spend
appliancerefrigerator299.99
appliancewashing machine219.80
electronicsvacuum341.00
electronicswireless headset249.90

Hints

Unlock
Clues

Hint 01: Filter transaction_date to 2022 before aggregating.
Hint 02: Group by category and product, then SUM(spend) AS total_spend.
Hint 03: Rank products within each category and keep ranks less than or equal to 2.

Solution

Locked
Answer

Solution is locked until you decide to reveal it. Try the editor first, then open this when you want the reference answer.

WITH product_totals AS (
  SELECT
    category,
    product,
    SUM(spend) AS total_spend
  FROM product_spend
  WHERE EXTRACT(YEAR FROM transaction_date) = 2022
  GROUP BY category, product
),
ranked_products AS (
  SELECT
    category,
    product,
    total_spend,
    RANK() OVER (
      PARTITION BY category
      ORDER BY total_spend DESC
    ) AS product_rank
  FROM product_totals
)
SELECT
  category,
  product,
  total_spend
FROM ranked_products
WHERE product_rank <= 2;

Explanation

Step By
Step

01

Filter the table to transactions that happened in 2022.

02

Group by category and product, then sum spend as total_spend.

03

Rank products inside each category by total_spend descending and keep the top two.

Related Questions

Keep
Solving