InterviewPrepKit

Home / SQL / Aggregation & Grouping

Region Share of Total Revenue

medium
Solving tips
  • Percentage-of-total needs two aggregates: the per-group sum and the grand total the groups share.
  • A window aggregate over the grouped result — SUM(SUM(x)) OVER () — gives the grand total without a second query or join.
  • Multiply by 100.0 (not 100) to force decimal division and avoid integer truncation.

Given a revenue log with several rows per region, report each region’s total revenue and what percentage of all revenue it represents.

Schema

CREATE TABLE orders (
  order_id INTEGER PRIMARY KEY,
  region   TEXT NOT NULL,
  amount   NUMERIC NOT NULL
);

Sample data:

order_idregionamount
1North100
2North200
3South300
4West400

Task

For each region, return:

  • region
  • region_total — the sum of amount for that region
  • pct_of_total — the region total as a percentage of the grand total across all regions, rounded to 2 decimal places

Order the result by pct_of_total descending, then region ascending.

Expected output

regionregion_totalpct_of_total
West40040.00
North30030.00
South30030.00
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.