// window reference

SQL cumulative percent of total

SUM(x) OVER (ORDER BY d) divided by SUM(x) OVER () gives each row's cumulative share: the Pareto distribution in two windows.

Categoría
Ventana
Returns
numeric fraction
In this category
35 of 79

Sintaxis

SUM(x) OVER (ORDER BY d) / NULLIF(SUM(x) OVER (), 0)

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

WITH ranked AS (
  SELECT customer_id, spend,
         SUM(spend) OVER (ORDER BY spend DESC, customer_id) AS cum,
         SUM(spend) OVER () AS total
  FROM customer_spend
)
SELECT customer_id, spend, cum,
       100.0 * cum / total AS cum_share
FROM ranked;

Conviene saberlo

  • Window calls cannot be nested (SUM(SUM(x) OVER ...) OVER ... is an error), but they can be combined in one expression: SUM(x) OVER (ORDER BY d) / SUM(x) OVER () is two separate windows divided.
  • Sorting by descending value gives the classic Pareto curve (80/20 check); ascending gives a growth curve. The denominator ignores ORDER BY because it has none.
  • Watch integer division and zero totals as in percent-of-total, plus peers: under the default RANGE frame, tied rows all show the cumulative share through the last of them. The tiebreaker in the example avoids that.

Questions about Cumulative Share

How do I find the rows that make up 80% of revenue?

Cumulative share ordered by spend DESC, then keep rows with cum_share <= 80 (the example scales by 100) in an outer query. One boundary row may straddle 80%; include or exclude it as a business rule.

Why does the total differ from my other report?

The denominator is the sum after WHERE. Filters applied to the query shrink it; compute the total in a separate unfiltered CTE when the base must stay fixed.

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.