SQL · Level 3 Window functions

SQL Percent of Total

Show each category's share of revenue with SUM() OVER (), and avoid the integer division that turns every percentage into 0.

  • SUM() OVER () is the grand total
  • Integer division truncates
  • 100.0 * part / total

SUM(x) OVER () puts the grand total on every row, so each row can show its share. Trap: dividing two integers gives an integer in SQL, so 30 / 40 is 0. Multiply by 100.0 first: 100.0 * 30 / 40 is 75.0.

SELECT team, wins,
       ROUND(100.0 * wins / SUM(wins) OVER (), 1) AS pct
FROM standings;

Return each category with its revenue (SUM(amount)) and its percentage of total revenue rounded to 1 decimal, highest revenue first. In the database below, books make 40 of 100, so 40%.

Sample data from the first test. The other tests use different rows, so write a query, not a list of answers.

sales 4 rows
idINTEGERcategoryTEXTamountINTEGER
1books30
2games50
3books10
4toys10
solution.sql
Test Suites Pending
Output