pgsql百分比函数
时间: 2023-10-25 18:10:03 浏览: 212
在pgsql中,可以使用以下两种方法计算百分比:
1. 使用sum() over()函数:可以通过在查询中使用sum() over()函数来计算百分比。例如,可以使用以下SQL语句计算tmp表中每个type的百分比:
SELECT tmp.type AS type, tmp.num AS num,
CASE WHEN SUM(tmp.num) OVER () = 0 THEN '0.00%'
ELSE round(CAST((100.0 * tmp.num / SUM(tmp.num) OVER ()) AS NUMERIC), 2) || '%'
END AS percentage
FROM tmp;
2. 使用percentile_cont函数:可以使用percentile_cont函数来计算百分位数。例如,可以使用以下SQL语句计算给定列的中位数:
SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY col) FROM (VALUES (2), (3), (6)) AS a(col);
这将返回结果3,表示给定列的中位数。
请注意,以上示例仅供参考,具体的SQL语句可能需要根据实际情况进行调整。
#### 引用[.reference_title]
- *1* [postgreSql利用sum() over()计算分组百分比](https://blog.csdn.net/camary_niu/article/details/118539305)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* [【PostgreSQL】函数之百分位数&中位数:percentile_cont()](https://blog.csdn.net/qq_34105362/article/details/80650868)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item]
- *3* [pg数据库百分比处理](https://blog.csdn.net/magi1201/article/details/115719675)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文