令人惊讶的是,我找不到 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
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/