通过排名从订单中获取行百分位数

时间:2016-04-05 08:06:06

标签: mysql sql

我正试图获得一行的百分位值。

例如,如果有100行,并且一行基于ORDER BY位于第50位,那么它应该是第50百分位(我认为)。基于订单的行索引除以总行数。

以下获取行级别:

SET @rank=0; 
SELECT id,code,@rank:=@rank+1 AS rank 
FROM images 
ORDER BY 
    (select avg(value) 
     from ratings 
     where image_id = images.id and type = 1) 
DESC

我如何获得单行的百分位数? (WHERE id = :id

1 个答案:

答案 0 :(得分:0)

拼图中唯一缺失的部分是结果集中的总行数:

SET @rank=0; 
SELECT id,code,@rank:=@rank+1 AS rank,
       100.0 * @rank / (SELECT COUNT(*) FROM images) AS percentile
FROM images 
ORDER BY 
    (select avg(value) 
     from ratings 
     where image_id = images.id and type = 1) 
DESC