Can someone indicate me how to install analytic functions and especially the ratio_to_report function in a Postgres database ?
I have tried to search in the postgres supplied modules but I didn't see the module that contains the function.
RATIO_TO_REPORT
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_report
FROM tab
SqlFiddleDemo
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_report
FROM tab
SqlFiddleDemo2
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               ║
╚═════╩══════╩═══════════╩═════════════════╝
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With