Quick Overview

This question evaluates proficiency with SQL aggregation and JOINs, analytic/window functions (RANK()), tie and NULL/edge-case handling, and percent-of-total calculations for per-customer spend analysis.

Find top-spend categories per customer with ranking

Company: Amazon

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: medium

Interview Round: Onsite

Using the schema and sample data below, write a single ANSI SQL query (CTEs allowed; no temp tables) that returns, for each customer, their top 2 product categories by total spend. Output columns: customer_id, category, total_spend, earliest_order_date, rank_in_customer. Requirements: - total_spend = SUM(oi.qty * oi.unit_price) per (customer_id, category). - earliest_order_date = MIN(o.order_date) within that (customer_id, category). - Use RANK() OVER (PARTITION BY customer_id ORDER BY total_spend DESC, earliest_order_date ASC) as rank_in_customer. - Return rows where rank_in_customer <= 2, including all ties at rank 2. - Include customers with no orders as a single row: category = NULL, total_spend = 0, earliest_order_date = NULL, rank_in_customer = NULL (do not assign rank for zero-spend customers). Hint: careful LEFT JOINs and conditional ranking. - Avoid vendor-specific extensions beyond standard window functions. Follow-ups (closely related; keep as part of the same query via additional columns/CTEs): A) Add percent_of_total = total_spend / SUM(total_spend) OVER (PARTITION BY customer_id), and ensure it is 0 for customers with no orders. B) Return only customer_ids whose top category’s percent_of_total < 0.5 (i.e., their spend is not dominated by a single category). Schema: customers(id INT PK, name TEXT) orders(id INT PK, customer_id INT FK -> customers.id, order_date DATE) order_items(id INT PK, order_id INT FK -> orders.id, product_id INT FK -> products.id, qty INT, unit_price DECIMAL(10,2)) products(id INT PK, category TEXT, name TEXT) Sample data: customers id | name 1 | Alice 2 | Bob 3 | Cara 4 | Dana orders id | customer_id | order_date 101 | 1 | 2025-07-02 102 | 1 | 2025-07-15 103 | 2 | 2025-07-20 104 | 2 | 2025-07-21 105 | 3 | 2025-07-22 order_items id | order_id | product_id | qty | unit_price 1001 | 101 | 201 | 2 | 10.00 1002 | 101 | 202 | 1 | 20.00 1003 | 102 | 201 | 1 | 10.00 1004 | 102 | 203 | 5 | 5.00 1005 | 103 | 202 | 2 | 20.00 1006 | 104 | 203 | 10 | 5.00 1007 | 105 | 204 | 1 | 100.00 products id | category | name 201 | CatA | A 202 | CatA | B 203 | CatB | C 204 | CatC | D

Overview: This question evaluates proficiency with SQL aggregation and JOINs, analytic/window functions (RANK()), tie and NULL/edge-case handling, and percent-of-total calculations for per-customer spend analysis.

Using the tables and sample data below, write a single ANSI SQL query (CTEs allowed; no temp tables) that returns, for each customer, their top 2 product categories by total spend. Output columns: - customer_id - category - total_spend - earliest_order_date - rank_in_customer - percent_of_total Rules: 1) total_spend = SUM(order_items.qty * order_items.unit_price) per (customer_id, category). 2) earliest_order_date = MIN(orders.order_date) within that (customer_id, category). 3) rank_in_customer must be computed as: RANK() OVER (PARTITION BY customer_id ORDER BY total_spend DESC, earliest_order_date ASC) 4) Return rows where rank_in_customer <= 2, including all ties at rank 2. 5) Include customers with no orders as a single row with: category = NULL, total_spend = 0, earliest_order_date = NULL, rank_in_customer = NULL, percent_of_total = 0. (Do not assign a rank for zero-spend customers.) 6) percent_of_total = total_spend / SUM(total_spend) OVER (PARTITION BY customer_id). Ensure it is 0 for customers with no orders. 7) Final filter: return only customer_ids whose TOP category’s percent_of_total < 0.5 (i.e., their spend is not dominated by a single category). Customers with no orders should be treated as having top category percent_of_total = 0. Use only standard SQL features (window functions are allowed).

Tables

customers(id INT, name VARCHAR(100))

orders(id INT, customer_id INT, order_date DATE)

order_items(id INT, order_id INT, product_id INT, qty INT, unit_price DECIMAL(10,2))

products(id INT, category VARCHAR(50), name VARCHAR(100))

Hints

  1. Aggregate spend and earliest order date per (customer_id, category) first, then apply window functions.
  2. Use RANK() and filter rank_in_customer <= 2 to keep ties at rank 2.

Community answers

Answer by MsMeow

with cte as (select a.name as customer_name, b.customer_id, b.order_date, b.id as order_id , min(order_date) over(partition by category, customer_id) as earliest_order_date, c.product_id, c.qty, c.unit_price, d.category, round(sum(c.qty*c.unit_price) over(partition by b.customer_id, d.category),0) as total_spend from customers a LEFT join orders b on a.id = b.customer_id left join order_items c on b.id = c.order_id left join products d on c.product_id = d.id), cte2 as (select category, customer_id, earliest_order_date, round(100*total_spend/nullif(sum(total_spend) OVER(PARTITION BY CATEGORY), 0),2) as pct, rank() over(partition by category order by total_spend desc) as rank_in_customer, total_spend from cte ORDER BY CATEGORY, TOTAL_SPEND DESC) select DISTINCT * from cte2 WHERE rank_in_customer <=2
AmazonData ScientistmediumData Manipulation (SQL/Python)

Top-2 spend categories per customer with ranking, percent-of-total, and dominance filter

Using the tables and sample data below, write a single ANSI SQL query (CTEs allowed; no temp tables) that returns, for each customer, their top 2 product categories by total spend.

Output columns:

  • customer_id
  • category
  • total_spend
  • earliest_order_date
  • rank_in_customer
  • percent_of_total

Rules:

  1. total_spend = SUM(order_items.qty * order_items.unit_price) per (customer_id, category).
  2. earliest_order_date = MIN(orders.order_date) within that (customer_id, category).
  3. rank_in_customer must be computed as: RANK() OVER (PARTITION BY customer_id ORDER BY total_spend DESC, earliest_order_date ASC)
  4. Return rows where rank_in_customer <= 2, including all ties at rank 2.
  5. Include customers with no orders as a single row with: category = NULL, total_spend = 0, earliest_order_date = NULL, rank_in_customer = NULL, percent_of_total = 0. (Do not assign a rank for zero-spend customers.)
  6. percent_of_total = total_spend / SUM(total_spend) OVER (PARTITION BY customer_id). Ensure it is 0 for customers with no orders.
  7. Final filter: return only customer_ids whose TOP category’s percent_of_total < 0.5 (i.e., their spend is not dominated by a single category). Customers with no orders should be treated as having top category percent_of_total = 0.

Use only standard SQL features (window functions are allowed).

Expected Output

Each returned row is one of the (up to) top-2 ranked categories per qualifying customer (including ties at rank 2), with spend, earliest order date for that category, the category rank within the customer, and percent of that customer's total spend. Customers with no orders appear as one row with NULL category, 0 spend, NULL dates/rank, and percent_of_total = 0. Additionally, only customers whose top category percent_of_total is < 0.5 are included.

Tables

customersordersorder_itemsproducts
customers
ColumnType
idINT
nameVARCHAR(100)
orders
ColumnType
idINT
customer_idINT
order_dateDATE
order_items
ColumnType
idINT
order_idINT
product_idINT
qtyINT
unit_priceDECIMAL(10,2)
products
ColumnType
idINT
categoryVARCHAR(50)
nameVARCHAR(100)

Comments (2)

Submit your answer

Approved first answer today earns 30 XP
Bold⌘BItalic⌘IInline code⌘`Bullet listTab to nest (○ ■)Numbered listTab to nest (a. i.)QuoteCode block
Formatting help
Language
Run code to see results here.

Browse More Questions