Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres ratio_to_report function

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.

like image 326
François Vanhille Avatar asked Feb 07 '23 12:02

François Vanhille


1 Answers

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               ║
╚═════╩══════╩═══════════╩═════════════════╝
like image 107
Lukasz Szozda Avatar answered Feb 10 '23 00:02

Lukasz Szozda