function - postgresql中的第n个百分位数计算

标签 function postgresql percentile

令人惊讶的是,我找不到 postgresql 的第 n 个百分位数函数。

我通过 mondrian olap 工具使用它,所以我只需要一个返回第 95 个百分位数的聚合函数。

我确实找到了这个链接:

http://www.postgresql.org/message-id/162867790907102334r71db0227jfa0e4bd96f48b8e4@mail.gmail.com

但由于某些原因,该百分位函数中的代码在某些情况下会在某些查询中返回空值。我检查了数据,数据中似乎没有任何奇怪的原因!

最佳答案

PostgreSQL 9.4 现在原生支持百分位数,在Ordered-Set Aggregate Functions 中实现:

percentile_cont(fraction) WITHIN GROUP (ORDER BY sort_expression) 

continuous percentile: returns a value corresponding to the specified fraction in the ordering, interpolating between adjacent input items if needed

percentile_cont(fractions) WITHIN GROUP (ORDER BY sort_expression)

multiple continuous percentile: returns an array of results matching the shape of the fractions parameter, with each non-null element replaced by the value corresponding to that percentile

有关详细信息,请参阅文档:http://www.postgresql.org/docs/current/static/functions-aggregate.html

并在此处查看一些示例:https://github.com/michaelpq/michaelpq.github.io/blob/master/_posts/2014-02-27-postgres-9-4-feature-highlight-within-group.markdown

CREATE TABLE aa AS SELECT generate_series(1,20) AS a;
--SELECT 20

WITH subset AS (
    SELECT a AS val,
        ntile(4) OVER (ORDER BY a) AS tile
    FROM aa
)
SELECT tile, max(val)
FROM subset GROUP BY tile ORDER BY tile;

 tile | max
------+-----
    1 |   5
    2 |  10
    3 |  15
    4 |  20
(4 rows)

关于function - postgresql中的第n个百分位数计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14316562/

相关文章:

sql - 使用 postgres db 进行适当的索引

postgresql - 如何将 jsonb 列扫描到结构/指针的一部分?

python - 使用 python 从 beta 分布获取分位数

sql - HIVE中的百分位计算

c++ - 根据 C++ 中的参数动态绑定(bind)到函数

function - Cocos2d : Calling function from one CCLayer in another (parent? ) CCLayer

postgresql - 无法从 Golang 容器连接到 Postgres docker 容器

Python:Matplotlib - 多个数据集的概率图

c++ - 函数参数的评估顺序

python - 如何从Python中的单个input()函数获取多个输入?