How would you compute a ratio-to-report or share-of-total metric using aggregate window functions?
Last updated
Divide each row's value by a windowed total:
value / SUM(value) OVER (...)repeats the total on every row without collapsing rows.Use
OVER ()for share of grand total, orOVER (PARTITION BY region)for share within each group.Guard divide-by-zero with
NULLIF(..., 0)and cast to decimal/float to avoid integer division truncating to 0.
- https://www.dawiso.com/glossary/sql-sum--over-complete-guide-to-window-functions-and-running-totals
- https://onestopde.com/master-sql-percentage-window-function-with-interview-questions/
- https://alexanderobregon.substack.com/p/calculating-percent-of-total-per
- https://www.sqlnoir.com/blog/sql-window-functions