【问题标题】:How to Get The Out-Of-Set Percentile In PostgreSQL?如何在 PostgreSQL 中获取超出设置的百分位数?
【发布时间】:2019-11-02 10:56:09
【问题描述】:

给定一张桌子

product1_id | score
A  |   2 
B  |   3

product2_id | score
W  |   1
X  |   2
Y  |   3
Z  |   4

如何使用 PostgreSQL 在 product2 分数中找到 product1 分数的超出设置百分位数以获得预期输出:

product1_id | score | out_of_set_percentile
A  |   2  |  50
B  |   3  |  75.

在python中解决这个问题的一种方法是合并表并应用scipy.percentileofscore

from scipy import stats
stats.percentileofscore([1, 2, 3, 4], 3)  # 75.0,

但我想要一种在 PostgreSQL 中本地执行此操作的方法

【问题讨论】:

    标签: python sql postgresql scipy percentile


    【解决方案1】:

    这是一种蛮力方法:

    select t1.product_id, t1.score,
           avg( (t2.score <= t1.score)::int ) as ratio
    from t1 cross join
         t2
    group by t1.product_id, t1.score;
    

    【讨论】:

      猜你喜欢
      • 2018-07-21
      • 2020-11-22
      • 2017-08-31
      • 2011-11-01
      • 2016-04-11
      • 1970-01-01
      • 2011-11-15
      • 2020-06-27
      • 2016-11-07
      相关资源
      最近更新 更多