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.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
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.