All problems

What Share of Revenue Does Each Category Own?

hardSQLWindow FunctionsJoins

Merchandising at Whetcode Supply is presenting a pie chart at the quarterly review, and a pie chart needs slices rather than totals. Three product categories are on sale, and the question is what portion of the shop's money each one is responsible for.

The difficulty is that every slice needs a number that belongs to the whole pie. A category's own revenue can be worked out from its own rows, but the denominator — everything the shop took — comes from all the rows at once, and it has to be available beside each category's figure rather than looked up separately and pasted in.

There is the usual split as well: an order says how many units were bought, and the price and the category are both facts about the product.

orders — one row per order. quantity is units bought. product_id points at a row in products.

id customer_id product_id quantity order_date
1 1 1 2 2023-02-01
2 1 4 1 2023-02-01
3 2 2 1 2023-02-10
4 3 3 3 2023-03-05
5 4 5 5 2023-03-11
6 1 3 1 2023-04-02
7 5 1 4 2023-05-20
8 2 5 2 2023-05-22
9 3 4 1 2023-06-01
10 5 2 1 2023-06-15

products — one row per product. category is the group it is sold under. price is the price of a single unit, in dollars.

id name category price
1 Wireless Mouse electronics 25.0
2 Standing Desk furniture 350.0
3 Desk Lamp furniture 40.0
4 Mechanical Keyboard electronics 85.0
5 Notebook Set office 12.0

Both tables already exist in the database — there is nothing to create or load.

Task: Write a query returning two columns, category and revenue_share, with one row per category that has sold at least one unit. revenue_share is that category's revenue divided by the revenue of the whole shop — a fraction between 0 and 1, not a percentage, rounded to 4 decimal places. An order's revenue is its quantity multiplied by the unit price of the product ordered. A category that has never sold anything produces no row rather than a row reading 0. Rows come back in alphabetical order of category.

Example output — shape only, on invented categories. The shares always come to 1 between them.

category revenue_share
lighting 0.5
stationery 0.1875
storage 0.3125

Sign in to solve this problem

Reading problems is free for everyone — solving them (Run, Submit, and tracking what you've solved) needs an account.

Sign in

Discussion

Sign in to join the discussion — reading is open to everyone.

Loading comments…