25. Revenue by category when a product sits in several

SQLMediumFan-out trapDuplicate trap

many-to-many · bridge table · allocation · joins

How the Colab notebook works

The notebook has the data, an answer cell and a check() function. You need a Google account; nothing is installed on your machine. Free Colab runs only two or three notebooks at a time, so end the session of a finished problem (Runtime > Disconnect and delete runtime) before opening the next one. "Mark as solved" is remembered in this browser only.

The situation

Finance wants revenue per product category. A product can be listed in more than one category: a travel adapter is in both Electronics and Travel.

The current report joins sales to categories and sums. Its category totals add up to far more than the company sold, because a sale of a product in three categories is counted three times. Finance wants totals that add up, so each sale is split evenly across the categories its product belongs to.

Input tables

sales

One row per sale.

Column Type Description
sale_id BIGINT Unique per sale.
product_id BIGINT The product sold.
amount DECIMAL(10,2) Sale value in rupees.

product_categories

Which product is in which category. A product can have several rows, or none. The table is maintained by hand and a few rows have been entered twice.

Column Type Description
product_id BIGINT The product.
category STRING A category the product is listed in.

Requirement

Return revenue per category.

  • A sale is split evenly across the categories of its product. A sale of 900.00 for a product in three categories adds 300.00 to each of the three.
  • A row that appears twice in product_categories is still one category for that product.
  • Sales of a product with no category go to a category named Uncategorized.
  • The revenues of all rows add up to the total of all sales.
  • Do not round. Small differences beyond the sixth decimal are ignored by the check.

Expected output

One row per category, plus Uncategorized.

Column Type Description
category STRING
revenue DOUBLE The category's share of sales.

Solve it in the browser

This editor runs DuckDB inside your browser. Nothing is installed and nothing is sent to a server. DuckDB's SQL is close to Spark SQL but not identical. The Colab notebook runs real Spark.

query.sql DuckDB, in your browser
Ctrl + Enter runs the query

Your result appears here. Your draft is kept in this browser.

Explanation

Show explanationGives the answer away. Try the problem first.

The approach

A join returns one row per match. A sale of a product in three categories comes out of the join as three rows, each carrying the full amount. Sum them and the sale has been counted three times.

There are two honest ways to report this:

  • Count the sale fully in every category, and say clearly that the categories overlap and must never be added together.
  • Allocate the sale: give each category a share, so the shares add back up to the sale.

Finance asked for the second, with an even split. Three steps:

  1. Clean the mapping: SELECT DISTINCT product_id, category. The table has rows that were entered twice.
  2. Count the categories per product from that clean mapping.
  3. Join sales to the mapping, divide each amount by the product's category count, and sum per category.

Both joins are LEFT joins. A product with no category matches nothing, keeps its row with a NULL category, and is reported as Uncategorized with its full amount (COALESCE(category_count, 1)).

A check you can run on any allocation: the output must add up to the input. Here both are 1,227,458.00.

The amount is cast to DOUBLE before dividing. A third of a rupee has no exact decimal form, and the statement asks for a DOUBLE. Without the cast Spark returns DECIMAL(38,23) and the check reports the type.

Common wrong answers

Join and sum. The category totals add up to 2,003,776.00 for sales of 1,227,458.00. Five of the six rows are wrong; only Uncategorized is right, because those sales match nothing and cannot be multiplied.

Join and sum on the de-duplicated mapping. Still 1,859,539.00. Removing the repeated rows fixes the accident. The fan-out from products that really are in several categories is still there.

Splitting, but on the raw mapping. Product 5 is in three categories, and its Travel row is entered twice, so the raw table has four rows for it. Count four and join to four: the sale is split in quarters, and Travel gets two of them. The total is still exactly right, 1,227,458.00, so the add-up check passes. Three categories are wrong.

De-duplicating in one place and not the other.

  • Join to the clean mapping, count from the raw table: the shares are too small. The total drops to 1,173,676.33 and three categories are wrong.
  • Count from the clean mapping, join to the raw table: the repeated rows each get a full share. Two categories are too high.

Clean the mapping once, in a CTE, and use only that.

Inner joins. The four uncategorised products vanish. The result has 5 rows and 147,207.00 of revenue (31 sales) is not in the report at all.

Rounding each share to 2 decimals. A sale of 100.00 in three categories becomes 33.33 three times, and a paisa is gone. Over the 24 sales of three-category products the total drifts to 1,227,458.03, and four rows fail the check. Sum first, round at the end if you must. If the shares have to be exact to the paisa, the usual method is to give the remainder to one of the categories.

Is an even split right?

That is a business decision, not a technical one. Other rules are common: all revenue to a product's primary category, or a weight per category. The technique is the same in every case: each sale gets weights that add up to 1.

What is never right is a report where overlapping totals are shown side by side with a grand total, and nobody is told they overlap.

Edge cases in the data

Case Where What it catches
Products in two categories 8 products Join and sum.
Products in three categories products 5, 14, 22 Join and sum; rounding the shares.
Mapping rows entered twice products 5, 9, 17 Counting or joining on the raw mapping.
A repeated row for a one-category product product 17 Its sales are split in two halves that land in the same category: harmless by luck.
Products with no category 27 to 30 Inner joins; a missing Uncategorized row.