Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
QA interview question
Databases, SQL & BISQL languageMiddleCommonPractical

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

Solution · Percent of total
Dialect · Portable SQLRuntime · SQLite sample DB

Runs against the resettable SQLite sample database used by the playground.

SQL
SQLite · sample DB · browser sandbox
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.

#sql#aggregation#window-functions#percentage

Sources

PostgreSQL documentationPostgreSQL Global Development Group · Relational modelling, SQL, joins, constraints, transactions, concurrency, indexes, query plans and recovery