Postgres ratio_to_report 函数
Postgres ratio_to_report function
谁能告诉我如何在 Postgres 数据库中安装分析函数,尤其是 ratio_to_report 函数?
我试图在 postgres 提供的模块中搜索,但我没有看到包含该函数的模块。
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.
您根本不需要导入特定的函数。使用窗口 SUM
:
的 Postgresql 等价物
SELECT ID, val, 1.0 * val / NULLIF(SUM(val) OVER(),0) AS ratio_to_report
FROM tab
输出:
╔═════╦══════╦═════════════════════╗
║ id ║ val ║ ratio_to_report ║
╠═════╬══════╬═════════════════════╣
║ 1 ║ 10 ║ 0.16666666666666666 ║
║ 2 ║ 10 ║ 0.16666666666666666 ║
║ 3 ║ 20 ║ 0.3333333333333333 ║
║ 4 ║ 20 ║ 0.3333333333333333 ║
╚═════╩══════╩═════════════════════╝
要模拟 PARTITION BY
,您可以使用:
SELECT ID, val, category,
1.0 * val / NULLIF(SUM(val) OVER(PARTITION BY category),0) AS ratio_to_report
FROM tab
输出:
╔═════╦══════╦═══════════╦═════════════════╗
║ 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 ║
╚═════╩══════╩═══════════╩═════════════════╝
谁能告诉我如何在 Postgres 数据库中安装分析函数,尤其是 ratio_to_report 函数?
我试图在 postgres 提供的模块中搜索,但我没有看到包含该函数的模块。
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.
您根本不需要导入特定的函数。使用窗口 SUM
:
SELECT ID, val, 1.0 * val / NULLIF(SUM(val) OVER(),0) AS ratio_to_report
FROM tab
输出:
╔═════╦══════╦═════════════════════╗
║ id ║ val ║ ratio_to_report ║
╠═════╬══════╬═════════════════════╣
║ 1 ║ 10 ║ 0.16666666666666666 ║
║ 2 ║ 10 ║ 0.16666666666666666 ║
║ 3 ║ 20 ║ 0.3333333333333333 ║
║ 4 ║ 20 ║ 0.3333333333333333 ║
╚═════╩══════╩═════════════════════╝
要模拟 PARTITION BY
,您可以使用:
SELECT ID, val, category,
1.0 * val / NULLIF(SUM(val) OVER(PARTITION BY category),0) AS ratio_to_report
FROM tab
输出:
╔═════╦══════╦═══════════╦═════════════════╗
║ 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 ║
╚═════╩══════╩═══════════╩═════════════════╝