sql - Postgresql:获取百分位并计算每个图 block 中有多少个

标签 sql postgresql percentile quantile

我生成了以下结果集

"degree_easy","degree_hard","easy_percent","hard_percent"
1,5,0.166667,0.833333
1,5,0.166667,0.833333
1,6,0.142857,0.857143
1,8,0.111111,0.888889

以上结果集是根据以下查询生成的:

select * from (
    select degree_one as degree_easy, 
        (degree_two + degree_three) as degree_hard,
        (degree_one::real/(degree_one::real + degree_two::real + degree_three::real)) 
            as easy_percent, 
        ((degree_two::real + degree_three::real)/(degree_one::real + degree_two::real +
            degree_three::real)) as hard_percent FROM recommendation_degree
    ) as dc 
where dc.degree_easy >= 1 and dc.degree_hard >= 1
order by dc.easy_percent ASC, dc.hard_percent ASC

现在我想做的是计算百分位数:

我不确定上面的哪一列更有意义,但假设我想使用 Degree_easy 和 Degree_hard 来计算百分位数或至少其中之一如何在 postgres 中使用 ntile 函数这样做吗?

执行以下操作的最佳实践是什么:

percentile, number_of_users
25, 4
50, 10
75, 20
99, 20

最佳答案

ntile 可以判断您是否位于有序列表的最后 25% 中。但它不支持权重。要使 ntile 正常工作,所有组的大小必须相等。

您可以使用sum ... over分析函数来计算权重。运行总和(值等于或小于当前行的所有行的总和)为:

sum(col1) over (order by col1)

整个表格的总和是:

sum(col1) over ()

您可以通过将运行总和与总和进行比较来计算百分位。一个简化的例子:

create table people (id serial, points int);
-- 3 people with 1 point, 2 people with 2 points, 1 person with 3 points
-- total 6 people and 10 points
insert into people (points) values (1), (1), (1), (2), (2), (3);

select  *
,       case 
        when sum(points) over (order by points) > 0.75 * sum(points) over () then '100%'
        when sum(points) over (order by points) > 0.5 * sum(points) over () then '75%'
        when sum(points) over (order by points) > 0.25 * sum(points) over () then '50%'
        else '25%'
        end as Percentile
from    people

打印内容:

ID    POINTS  PERCENTILE
1     1       50%
2     1       50%
3     1       50%
4     2       75%
5     2       75%
6     3       100%

获得 1 分的人总共获得 3 分,即总数的 30%。这使他们处于 50% 的百分位。得2分的人总数达到7人,进入前75%。得 3 分的人使总分达到 10 分,进入最高分。

Example at SQL Fiddle.

关于sql - Postgresql:获取百分位并计算每个图 block 中有多少个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25433051/

相关文章:

sql - 联合所有具有不同列数的查询

MySQL 似乎不能正常工作

database - pgAdmin数据库还原

java - Apache Commons Math 2.2 百分位数错误?

scala - 百分位数计算器

sql - 在 SQL 中计算百分位数

sql - 透视带有文本且无聚合的表

sql - 事务在触发器中结束 批处理已中止

java - 如何查询postgres数据库以获取特定坐标10公里半径内的所有点

postgresql - SQLAlchemy/Flask/PostgreSQL 池连接