Write SQL to calculate each group's percentage of the overall total.
Answer
Aggregate to the required group grain first, then divide each group total by a window SUM over the aggregated rows. Cast or multiply by a decimal value when the database would otherwise perform integer division, and define how zero totals and NULL amounts should be handled.
Strong answer includes
- aggregates to the intended grain before calculating the share
- uses a window total rather than a second independent query
- handles numeric type, zero-denominator and NULL behavior
Practical example
Dialect · Portable SQLRuntime · SQLite sample DB
Runs against the resettable SQLite sample database used by the playground.
SQL
Result
Run the query to see the result.
Aggregate each group, then window-sum those aggregate results for the denominator. NULLIF prevents division by zero when the total is zero.
Expected result: One row per group with its aggregate and share of the grand total.