// 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.

Categoría
Ventana
Returns
numeric
In this category
34 of 79

Sintaxis

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

Soporte del motor

MotorSupportNotas
SQL Server Sí Supported under this name.
PostgreSQL Sí Supported under this name.
MySQL Sí MySQL 8.0+
SQLite Sí SQLite 3.25+
Oracle Sí Supported under this name.

Ejemplos

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;

Conviene saberlo

  • 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.