// window reference

SQL Oracle RATIO_TO_REPORT

RATIO_TO_REPORT(x) OVER (partition) returns x / SUM(x) in that partition, the percent-of-total pattern as a built-in analytic.

Categoria
Janela
Returns
NUMBER (a fraction; 0 to 1 for non-negative values)
In this category
77 of 79

Sintaxe

RATIO_TO_REPORT(amount) OVER (PARTITION BY region)

Suporte a mecanismos

MotorSupportNotas
SQL Server Not built in use amount * 1.0 / NULLIF(SUM(amount) OVER (PARTITION BY ...), 0)
PostgreSQL Not built in use amount * 1.0 / NULLIF(SUM(amount) OVER (PARTITION BY ...), 0)
MySQL Not built in MySQL 8.0+: use amount / SUM(amount) OVER (PARTITION BY ...)
SQLite Not built in use amount * 1.0 / SUM(amount) OVER (PARTITION BY ...)
Oracle Sim Oracle-only analytic; other engines use the SUM OVER division pattern

Exemplos

Oracle

SELECT region, amount,
       RATIO_TO_REPORT(amount) OVER (PARTITION BY region) AS region_share,
       RATIO_TO_REPORT(amount) OVER () AS company_share
FROM sales;

Any engine

-- the portable form
SELECT region, amount,
       amount * 1.0 / NULLIF(SUM(amount) OVER (PARTITION BY region), 0) AS region_share
FROM sales;

Bom saber

  • NULL behaves as in the hand-rolled division: a NULL x gives a NULL ratio, and NULLs are left out of the partition sum.
  • A partition whose values sum to 0 yields NULL rather than an error, while x / SUM(x) OVER (...) raises divide-by-zero on Oracle, SQL Server and PostgreSQL (MySQL and SQLite return NULL).
  • The portable equivalent everywhere is the two-window division: amount * 1.0 / NULLIF(SUM(amount) OVER (PARTITION BY g), 0); see percent-of-total.

Questions about RATIO_TO_REPORT

What is the portable replacement for RATIO_TO_REPORT?

Divide the row by its partition sum: amount * 1.0 / NULLIF(SUM(amount) OVER (PARTITION BY g), 0). Watch integer division and the zero-sum guard.

How does RATIO_TO_REPORT handle NULL and zero sums?

NULL inputs give NULL ratios, and a zero-sum partition gives NULL for every row instead of an error. The manual division needs NULLIF to match that.

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