Cod*_*dek 22 postgresql function percentile
我出乎意料地无法找到postgresql的第n个百分位函数.
我通过mondrian olap工具使用这个,所以我只需要一个返回95%的聚合函数.
我找到了这个链接:
http://www.postgresql.org/message-id/162867790907102334r71db0227jfa0e4bd96f48b8e4@mail.gmail.com
但由于某些原因,该百分位函数中的代码在某些情况下使用某些查询返回空值.我已经检查了数据,数据中没有什么奇怪的东西会导致这种情况!
alf*_*onx 33
使用PostgreSQL 9.4,现在支持百分位数,在有序集合聚合函数中实现:
Run Code Online (Sandbox Code Playgroud)percentile_cont(fraction) WITHIN GROUP (ORDER BY sort_expression)
连续百分位数:返回与排序中指定分数对应的值,如果需要,在相邻输入项之间进行插值
Run Code Online (Sandbox Code Playgroud)percentile_cont(fractions) WITHIN GROUP (ORDER BY sort_expression)
multiple continuous percentile:返回与fractions参数的形状匹配的结果数组,每个非null元素由对应于该百分位数的值替换
有关更多详细信息,请参阅文档: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
Mik*_*ike 19
该ntile
功能在这里非常有用.我有一张桌子test_temp
:
select * from test_temp
score
integer
3
5
2
10
4
8
7
12
select score, ntile(4) over (order by score) as quartile from test_temp;
score quartile
integer integer
2 1
3 1
4 2
5 2
7 3
8 3
10 4
12 4
Run Code Online (Sandbox Code Playgroud)
ntile(4) over (order by score)
按分数对列进行排序,将其拆分为四个偶数组(如果数字均匀分配),并根据顺序分配组编号.
由于我这里有8个数字,它们代表第0个,第12.5个,第25个,第37.5个,第50个,第62.5个,第75个和第87.5个百分位数.因此,如果我只将结果取quartile
为2,那么我将得到第25和37.5百分位数.
with ranked_test as (
select score, ntile(4) over (order by score) as quartile from temp_test
)
select min(score) from ranked_test
where quartile = 2
group by quartile;
Run Code Online (Sandbox Code Playgroud)
返回4
,列表中的第三个最高数字8.
如果您有一个较大的表并使用ntile(100)
过滤的列将是百分位数,您可以使用与上面相同的查询.