sqlcmd.net validated sql reference
advanced windowing MySQL MariaDB SQL Server PostgreSQL

Calculate Percent Of Total With A Window Function

Use `SUM(...) OVER ()` to compare each row's value to the total without collapsing the result set.

Docker-validated Not currently validation-green

Show each category as a share of total sales

The total sales amount is 200. Music contributes 100 of 200, or 50%. Games contributes 30%, and Books contributes 20%. The window function keeps each original row while making the total available to every row.

Rows loaded before the example query runs.
Setup
CREATE TABLE sales (category VARCHAR(20), amount INT);

INSERT INTO
  sales (category, amount)
VALUES
  ('Books', 40),
  ('Games', 60),
  ('Music', 100);
Shared across supported engines.
SQL
SELECT
  category,
  amount,
  ROUND(amount * 100.0 / SUM(amount) OVER (), 1) AS pct_of_total
FROM
  sales
ORDER BY
  amount DESC;
Returned rows for the shared example.
categoryamountpct_of_total
Music10050
Games6030
Books4020

All supported engines use the same window-function pattern here and return the same percentages.

Where this command helps.

  • showing each category's contribution to a total
  • adding percent-of-total metrics to a report without a separate aggregate query

What the command is doing.

A percent-of-total calculation is a good fit for window functions because you usually want to keep each row while also referencing the grand total. SUM(amount) OVER () computes that total once across the full result set, and each row can divide its own value by the shared total to produce a percentage.