Calculate Top Customer Revenue Share and 7-Day Growth by Product Model
SQL & DataModel answerLast updated
Write a SQL query to compute 7-day revenue growth and identify top spenders per product model with tie-breaking logic based on historical purchase date.
You are analyzing weekly product metrics for an e-commerce platform. Assume the reference evaluation date (today) is 2025-09-01.
Write a SQL query that fulfills the following business logic:
-
Model Revenue Metrics: For each product model, calculate:
- Current 7-Day Revenue (
curr_revenue): Sum of revenue from2025-08-26to2025-09-01inclusive. - Previous 7-Day Revenue (
prev_revenue): Sum of revenue from2025-08-19to2025-08-25inclusive. - Growth Rate (
growth_rate): The period-over-period revenue change ratio calculated as(curr_revenue - prev_revenue) / prev_revenue. Handle zero denominators gracefully to avoid division by zero.
- Current 7-Day Revenue (
-
Top Customer Breakdown: For each product model, identify up to the top 3 customers by spend in the current 7-day window (
2025-08-26to2025-09-01inclusive). Include:customer_idandcustomer_namecustomer_spend: Total revenue generated by the customer for that model in the current window.customer_share_pct: The percentage share of the customer's spend relative to the model's totalcurr_revenue.
-
Constraints & Rules:
- Exclude any orders where
status != 'completed'. revenuefor an order is defined asqty * unit_price.- Tie-Breaking Rule: When ranking top spenders for a model, break ties in
customer_spendby ordering by the customer's earliest completed purchase date (MIN(order_date)) for that specific model across all-time completed order history (not restricted to the current 7-day window). If a tie still exists, break it deterministically usingcustomer_idascending. - Models with no customer purchases in the current window should still appear in the output with NULL customer details (and
0for revenue aggregates).
- Exclude any orders where
Database Schema
models
model_id(integer)model_name(varchar)
customers
customer_id(integer)customer_name(varchar)country(varchar)
orders
order_id(integer)order_date(date/timestamp)customer_id(integer)model_id(integer)qty(integer)unit_price(numeric)status(varchar)
Expected Output Structure
model_namecurr_revenueprev_revenuegrowth_ratecustomer_idcustomer_namecustomer_spendcustomer_share_pct
Hints
Hint 1
Pre-filter for completed orders in a Common Table Expression (CTE) so downstream aggregations only evaluate valid transactions.
Hint 2
Be careful when calculating the first purchase date for tie-breaking: evaluating `MIN(order_date)` within the current 7-day window instead of all-time order history will lead to incorrect ranking.
Hint 3
Use `LEFT JOIN` when attaching top customers back to the model summary, and put the `rn <= 3` filter inside the `ON` clause to prevent dropping models that have zero sales in the current period.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Key Approach
This problem requires combining model-level trend analysis with partitioned customer rankings. The pipeline can be organized into clear CTE steps:
- Filtered Transactions (
completed): Filter out non-completed orders upfront and compute item-level revenue (qty * unit_price). - Model Aggregations (
model_rev): Calculate the current and previous 7-day totals per model using conditional aggregation (SUM(CASE WHEN ...)). Compute the growth rate usingNULLIF(prev_revenue, 0)to prevent division-by-zero errors. - Historical Tie-Breaker (
first_purchase): Derive each customer's overall first purchase date per model across all historical completed orders. - Window Customer Spend (
cust_spend): Sum spend per model and customer strictly within the current window (2025-08-26to2025-09-01). - Ranking (
ranked): Rank spenders usingROW_NUMBER() OVER (PARTITION BY model_id ORDER BY customer_spend DESC, first_purchase_date ASC, customer_id ASC). - Final Assembly:
LEFT JOINthe model summary to the ranked top-3 customers and join customer names.
SQL Query
WITH completed AS (
SELECT
order_id,
order_date,
customer_id,
model_id,
qty * unit_price AS revenue
FROM orders
WHERE status = 'completed'
),
model_rev AS (
SELECT
m.model_id,
m.model_name,
COALESCE(SUM(CASE WHEN c.order_date >= DATE '2025-08-26'
AND c.order_date < DATE '2025-09-02'
THEN c.revenue ELSE 0 END), 0) AS curr_revenue,
COALESCE(SUM(CASE WHEN c.order_date >= DATE '2025-08-19'
AND c.order_date < DATE '2025-08-26'
THEN c.revenue ELSE 0 END), 0) AS prev_revenue
FROM models m
LEFT JOIN completed c ON m.model_id = c.model_id
GROUP BY m.model_id, m.model_name
),
first_purchase AS (
-- All-time first purchase date for tie-breaking
SELECT
model_id,
customer_id,
MIN(order_date) AS first_purchase_date
FROM completed
GROUP BY model_id, customer_id
),
cust_spend AS (
-- Spend in current 7-day window
SELECT
model_id,
customer_id,
SUM(revenue) AS customer_spend
FROM completed
WHERE order_date >= DATE '2025-08-26'
AND order_date < DATE '2025-09-02'
GROUP BY model_id, customer_id
),
ranked AS (
SELECT
cs.model_id,
cs.customer_id,
cs.customer_spend,
ROW_NUMBER() OVER (
PARTITION BY cs.model_id
ORDER BY
cs.customer_spend DESC,
fp.first_purchase_date ASC,
cs.customer_id ASC
) AS rn
FROM cust_spend cs
JOIN first_purchase fp
ON cs.model_id = fp.model_id
AND cs.customer_id = fp.customer_id
)
SELECT
mr.model_name,
mr.curr_revenue,
mr.prev_revenue,
ROUND(
(mr.curr_revenue - mr.prev_revenue)::numeric
/ NULLIF(mr.prev_revenue, 0),
4
) AS growth_rate,
r.customer_id,
cu.customer_name,
r.customer_spend,
ROUND(
100.0 * r.customer_spend / NULLIF(mr.curr_revenue, 0),
2
) AS customer_share_pct
FROM model_rev mr
LEFT JOIN ranked r
ON mr.model_id = r.model_id
AND r.rn <= 3
LEFT JOIN customers cu
ON r.customer_id = cu.customer_id
ORDER BY mr.model_name, r.rn;
Key Technical Considerations
- Timestamp Boundary Safety: Using half-open intervals (
order_date >= '2025-08-26' AND order_date < '2025-09-02') ensures that records recorded with timestamp components on2025-09-01(e.g.,2025-09-01 23:59:59) are correctly included without using problematicBETWEENpredicates. - Preserving Models without Sales: Filtering
r.rn <= 3inside theLEFT JOIN ... ONclause guarantees that models with zero activity in the current window still appear in the output with metric aggregates preserved (0revenue,NULLcustomer data). Placing this condition in a globalWHEREclause would convert the join to an inner join. - Determinism in Ranking:
ROW_NUMBER()is used overRANK()orDENSE_RANK()to strictly limit output to 3 rows per model. Usingcustomer_idas the final ORDER BY term guarantees deterministic output during ties.