Postgres ratio_to_report function
RATIO_TO_REPORT is an analytic function. It computes the ratio of a value to the sum of a set of values. If expr evaluates to null, then the ratio-to-report value also evaluates to null.
You don't need importing specific function at all. Postgresql equivalent using windowed SUM
:
SELECT ID, val, 1.0 * val / NULLIF(SUM(val) OVER(),0) AS ratio_to_reportFROM tab
Output:
╔═════╦══════╦═════════════════════╗║ id ║ val ║ ratio_to_report ║╠═════╬══════╬═════════════════════╣║ 1 ║ 10 ║ 0.16666666666666666 ║║ 2 ║ 10 ║ 0.16666666666666666 ║║ 3 ║ 20 ║ 0.3333333333333333 ║║ 4 ║ 20 ║ 0.3333333333333333 ║╚═════╩══════╩═════════════════════╝
To simulate PARTITION BY
you could use:
SELECT ID, val, category, 1.0 * val / NULLIF(SUM(val) OVER(PARTITION BY category),0) AS ratio_to_reportFROM tab
Output:
╔═════╦══════╦═══════════╦═════════════════╗║ id ║ val ║ category ║ ratio_to_report ║╠═════╬══════╬═══════════╬═════════════════╣║ 1 ║ 10 ║ a ║ 0.25 ║║ 2 ║ 10 ║ a ║ 0.25 ║║ 3 ║ 20 ║ a ║ 0.5 ║║ 4 ║ 20 ║ b ║ 1 ║╚═════╩══════╩═══════════╩═════════════════╝