KatInterview

Per-Category Top-10 Items: Revenue Share Analysis

SQL & DataModel answer
MediumModel answerSQL & Datawindow-functionsaggregationCTEs

Last 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:

  1. Identifies the top 10 items by total revenue (summed across all orders).
  2. 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.