Per-Category Top-10 Items: Revenue Share Analysis
SQL & DataModel answerLast updated
Write a SQL query ranking the top 10 items by revenue within each category and compute what fraction of each category's total revenue those items represent.
Setup
You have a single sales table that records individual orders:
sales
+----------+-------------+---------+---------+------------+
| order_id | category | item_id | revenue | order_date |
+----------+-------------+---------+---------+------------+
| 1001 | Books | B12 | 19.99 | 2023-07-01 |
| 1002 | Books | B45 | 9.99 | 2023-07-02 |
| 1003 | Toys | T88 | 29.99 | 2023-07-02 |
| 1004 | Toys | T12 | 15.99 | 2023-07-03 |
| 1005 | Electronics | E33 | 199.99 | 2023-07-03 |
+----------+-------------+---------+---------+------------+
Each row is one order. The same item can appear across many orders.
Task
Part 1 — SQL
Write a query that, for each category:
- Identifies the top 10 items by total revenue (summed across all orders).
- Returns one row per item showing:
category,item_id, the item's rank within its category, the item's total revenue, the category's total revenue (all items, not just the top 10), the item's percentage of category revenue, and the combined revenue share the top-10 items hold in that category.
Explain every choice you make: which ranking function you picked, where you compute the category total and why, and how you handle ties, NULLs, and categories with fewer than 10 items.
Part 2 — Concept: Normalization vs. Denormalization
The sales table stores category directly on every order row. Explain what normalization and denormalization mean, when you would choose each design, and what trade-offs each carries.
Part 3 — Design: ETL Pipeline
Outline the key steps of an ETL pipeline you would build to keep this sales table populated and reliable at scale.
Hints
Hint 1
An item spans many order rows — collapse to one row per (category, item_id) before you rank anything, otherwise you are ranking individual transactions, not items.
Hint 2
Compute the full category total as a window SUM before any top-10 filter; if you filter first and then sum, the denominator will only cover the survivors and every percentage will equal 100%.
Hint 3
ROW_NUMBER(), RANK(), and DENSE_RANK() each give a different answer when two items are tied at position 10 — decide which behavior the business actually wants and be ready to justify it.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core insight: aggregation order matters
This is a two-level aggregation problem. The two levels must stay in the right order or the percentage calculation breaks.
- Level 1 — item totals: collapse the order-level rows into one row per
(category, item_id). An item appearing on 50 orders must be ranked by its combined revenue, not by any single transaction. - Level 2 — ranking and category totals: within each category, rank items by their total revenue and attach the category-wide total using a window function. The category total must be computed here, before any row filtering, so it reflects every item in the category — not just the ones that survive the top-10 cut.
If you apply the WHERE rn <= 10 filter and then sum revenue, the denominator shrinks to match the numerator and every row shows 100%. That is the single most common mistake on this type of question.
SQL solution
WITH item_revenue AS (
-- Level 1: aggregate to one row per item per category
SELECT
category,
item_id,
SUM(revenue) AS item_revenue
FROM sales
WHERE revenue IS NOT NULL -- exclude NULLs before aggregating
GROUP BY category, item_id
),
ranked AS (
-- Level 2: rank items and capture the full category total before any filter
SELECT
category,
item_id,
item_revenue,
ROW_NUMBER() OVER (
PARTITION BY category
ORDER BY item_revenue DESC, item_id -- item_id breaks ties deterministically
) AS rn,
SUM(item_revenue) OVER (
PARTITION BY category
) AS category_revenue
FROM item_revenue
)
SELECT
category,
item_id,
rn AS item_rank,
item_revenue,
category_revenue,
ROUND(100.0 * item_revenue
/ NULLIF(category_revenue, 0), 2) AS item_pct_of_category,
SUM(item_revenue) OVER (PARTITION BY category) AS top10_revenue,
ROUND(100.0 * SUM(item_revenue) OVER (PARTITION BY category)
/ NULLIF(category_revenue, 0), 2) AS top10_pct_of_category
FROM ranked
WHERE rn <= 10
ORDER BY category, item_rank;
The final window SUM runs after the WHERE rn <= 10 filter, so top10_revenue sums only the surviving rows. category_revenue was stamped onto every row in ranked before any filter, so it still carries the full category total. The ratio of the two is the correct denominator-safe percentage.
One-row-per-category variant (if the interviewer only wants the rollup):
SELECT
category,
SUM(item_revenue) AS top10_revenue,
MAX(category_revenue) AS category_revenue,
ROUND(100.0 * SUM(item_revenue)
/ NULLIF(MAX(category_revenue), 0), 2) AS top10_pct
FROM ranked
WHERE rn <= 10
GROUP BY category;
Choosing the right ranking function
| Function | Behavior at a tie for position 10 | Items returned |
|---|---|---|
ROW_NUMBER() | Picks one arbitrarily (tie-break by item_id here) | Exactly 10 |
RANK() | Both tied items get rank 10; next item gets rank 12 | 10 or more |
DENSE_RANK() | Both get rank 10; next item gets rank 11 | 10 or more |
ROW_NUMBER with a deterministic tie-breaker is the right default for "give me exactly 10 items." Always ask the business whether ties should be included — the answer changes the query.
Edge cases to call out
- Fewer than 10 items in a category: all items are returned and
top10_pctequals 100%. That is correct. - NULL revenue: filtered out in the first CTE. Alternatively,
COALESCE(revenue, 0)if a zero-revenue order is meaningful. - Negative revenue (refunds): net revenue can pull the category total toward zero or below.
NULLIFprevents division by zero; decide whether refunds should offset item totals or be tracked separately. - NULL category: it forms its own partition. Decide whether to label it "Uncategorized" or exclude it with
WHERE category IS NOT NULL. - Date range: "top items overall" is rarely what the business means. Add
WHERE order_date BETWEEN :start AND :endin the first CTE to scope the analysis.
Complexity
GROUP BYinitem_revenue: O(n) with hash aggregation, where n is the number of order rows.- Window functions in
ranked: O(m log m) where m is the number of distinct items, because each partition is sorted. - Space: O(m) for the intermediate item table.
- At scale, partition or cluster the underlying table by
category(and optionally byorder_date) so each partition sort stays local and avoids a full shuffle.
Python equivalent (pandas)
import numpy as np
import pandas as pd
def top10_share(sales: pd.DataFrame, k: int = 10) -> pd.DataFrame:
# Level 1: item totals
item = (
sales.dropna(subset=["revenue"])
.groupby(["category", "item_id"], as_index=False)["revenue"]
.sum()
.rename(columns={"revenue": "item_revenue"})
)
# Level 2: category totals before any filter
item["category_revenue"] = (
item.groupby("category")["item_revenue"].transform("sum")
)
item = item.sort_values(
["category", "item_revenue", "item_id"],
ascending=[True, False, True]
)
item["item_rank"] = item.groupby("category").cumcount() + 1
top = item[item["item_rank"] <= k].copy()
top["top10_revenue"] = top.groupby("category")["item_revenue"].transform("sum")
top["top10_pct_of_category"] = (
100 * top["top10_revenue"]
/ top["category_revenue"].replace(0, np.nan)
).round(2)
return top.reset_index(drop=True)
Normalization vs. denormalization
Normalization stores each fact once across related tables (e.g., separate orders, items, categories tables in 3NF). Benefits: no update anomalies, compact storage, referential integrity. Cost: reads require joins. The right choice for OLTP systems — checkout, inventory — where writes are frequent and consistency is critical. Renaming a category should touch one row.
Denormalization duplicates attributes to eliminate joins at read time. The sales table here is denormalized: category is repeated on every order row. Benefits: fast, simple reads. Costs: redundancy and the risk of inconsistency on updates. The right choice for OLAP and reporting — dashboards, ML feature tables, this top-10 analysis — on columnar warehouses like Redshift or BigQuery, where scan speed matters more than write efficiency.
The standard pattern: keep normalized sources, then build denormalized warehouse models on top via a transformation layer.
ETL pipeline outline
- Extract: pull data incrementally from source systems (orders database, catalog service) using CDC or an
updated_atwatermark. Land raw files unchanged in object storage (e.g., S3), partitioned by date. - Validate: assert schema, check for NULLs in key columns (
order_id,item_id,category), confirmrevenue >= 0or flag explicit refunds, detect duplicateorder_idvalues. - Transform: join orders to a canonical item/category dimension to resolve any denormalization inconsistencies, apply business rules (e.g., exclude cancelled orders), and produce the clean
salesgrain. - Load: write to the warehouse incrementally (insert new partitions, upsert for late-arriving corrections). Avoid full-table rewrites in production.
- Test and monitor: data quality checks on row counts, revenue totals, and NULL rates after each run. Alert on anomalies (e.g., revenue dropping 50% versus the same day last week). Log lineage so any upstream change is traceable.