// window reference

SQL percent of total

Row divided by SUM(x) OVER (partition or empty) gives the share: group percentages without a separate totals query or join.

類別
視窗
Returns
numeric
In this category
34 of 79

語法

x * 100.0 / SUM(x) OVER (PARTITION BY g)

引擎支援

引擎Support備註
SQL Server 是 Supported under this name.
PostgreSQL 是 Supported under this name.
MySQL 是 MySQL 8.0+
SQLite 是 SQLite 3.25+
Oracle 是 Supported under this name.

範例

Any engine

SELECT region, amount,
       100.0 * amount / NULLIF(SUM(amount) OVER (), 0) AS share_of_all,
       100.0 * amount / NULLIF(SUM(amount) OVER (PARTITION BY region), 0) AS share_of_region
FROM sales;

小知識

  • Multiply by 100.0 (or cast) before dividing: on SQL Server, PostgreSQL and SQLite, integer / integer truncates and a share of 0 is the usual symptom. MySQL and Oracle return a decimal.
  • Guard the denominator with NULLIF when the total can be 0: SQL Server, PostgreSQL and Oracle raise a division-by-zero error, while MySQL and SQLite return NULL.
  • The empty OVER () is the grand total across all rows of the result after WHERE; filters shrink the denominator, which may or may not be the percentage you mean.

Questions about Percent of Total

Why is my percentage always 0 or 100?

Integer division: amount / total with both integers truncates on SQL Server, PostgreSQL and SQLite. Make the numerator decimal (amount * 1.0) before dividing.

Can I get percent of total with GROUP BY in the same query?

Yes: window functions run after grouping, so SELECT dim, SUM(x), 100.0 * SUM(x) / SUM(SUM(x)) OVER () FROM t GROUP BY dim works; the inner SUM is the group's, the outer one the grand total.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.