Percentage of Total Sales
Show each region's share of overall sales as a percentage.
Start practiceProblem statement
Prompt
Given the sales table below, write a query that returns, for each region, the percentage of overall sales that region contributes.
- Output columns:
regionandpct_of_total, rounded to 2 decimal places. - Order the result by
pct_of_totaldescending, then byregion. sales.amountmay beNULL;NULLamounts are ignored bySUM.
Example
| id | region | amount |
|---|---|---|
| 1 | North | 100 |
| 2 | North | 50 |
| 3 | South | 50 |
Total = 200. Expected result:
| region | pct_of_total |
|---|---|
| North | 75 |
| South | 25 |
Constraints
sales.idis the primary key.sales.amountis nullable.
Tips
- Aggregate to per-region totals, then use
SUM(region_total) OVER ()to broadcast the grand total to every row. amount * 100.0 / grand_totalkeeps the division in floating point so rounding behaves.
Schema
CREATE TABLE sales (
id INTEGER PRIMARY KEY,
region TEXT NOT NULL,
amount INTEGER -- NULL allowed
);
Sample data
INSERT INTO sales (id, region, amount) VALUES
(1, 'North', 100),
(2, 'North', 50),
(3, 'South', 50),
(4, 'East', 100),
(5, 'East', 50),
(6, 'West', 50);
Additional hidden fixtures are applied during validation to test edge cases.
Solution
One correct approach — try solving it yourself in the practice editor first, then compare. There is usually more than one valid solution.
-- Reference: each region's percentage of the overall total.
WITH region_totals AS (
SELECT region, SUM(amount) AS region_total
FROM sales
WHERE amount IS NOT NULL
GROUP BY region
)
SELECT region,
ROUND(region_total * 100.0 / SUM(region_total) OVER (), 2) AS pct_of_total
FROM region_totals
ORDER BY pct_of_total DESC, region;
Key concepts
- SUM OVER ()
- Window aggregation
- ROUND
Related questions
- mediumFirst and Last Order Per CustomerShow the date of each customer's first and last order.
- mediumGame Play Analysis IVFind the fraction of players who logged in the day after their first login.
- mediumImmediate Food DeliveryReport the percentage of customers' first orders that were delivered immediately.
- mediumRunning TotalCompute a running total of sales over time, partitioned per account.
- mediumSeven-Day Rolling AverageCompute each sale's 7-day rolling average of amount, per account.