Postgres ratio_to_report function

后端 未结 1 1797
青春惊慌失措
青春惊慌失措 2021-01-14 06:30

Can someone indicate me how to install analytic functions and especially the ratio_to_report function in a Postgres database ?

I have tried to searc

相关标签:
1条回答
  • 2021-01-14 07:09

    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               ║
    ╚═════╩══════╩═══════════╩═════════════════╝
    
    0 讨论(0)
提交回复
热议问题