MySQL-百分位数计算并在同一表的其他列中进行更新

时间:2018-11-29 12:03:25

标签: mysql sql phpmyadmin percentile

我在MySQL(phpMYAdmin)中有一个带有以下列的表

MySQL Table

我试图确定每一行的百分位数,并在G1Ptile列中更新该值。 G1Ptile列是基于G1%的百分比计算。我根据here

的John Woo的回答使用以下内容
SELECT  `G1%`, 
       (1-ranks/totals)*100 Percentile FROM (
SELECT  distinct `G1%`,
        @rank:=@rank + 1 ranks,
        (SELECT COUNT(*) FROM PCount) totals
FROM    PCount a,
        (SELECT @rank:=0) s
ORDER   BY `G1%` DESC ) s;

并获得以下输出

Output

输出在select语句中,我希望能够将其更新到表中的G1Ptile列,但是我无法使用

更新它
UPDATE `PCount` SET `G1Ptile`= --(All of the select query mentioned above) 

请帮助您修改查询/建议替代方法,以便我可以使用通过上述查询获得的百分位值并将其更新为同一表中的G1Ptile。我还有一个问题,就是G1%中有两个20%的值,但是分配给一个的百分位数是20,另一个的百分位是30。我希望它们都为20,而系列的下一行为30。 / p>

1 个答案:

答案 0 :(得分:1)

我会将您的计算结果写为:

SELECT `G1%`, 
       (1 - ranks / totals) * 100 as Percentile
FROM (SELECT `G1%`,
              (@rank := @rank + 1) ranks,
              (SELECT COUNT(*) FROM PCount) as totals
      FROM (SELECT DISTINCT `G1%`
            FROM PCount
            ORDER BY `G1%` DESC
           ) p CROSS JOIN
           (SELECT COUNT(*) as totals, @rank := 0
            FROM Pcount
           ) params
     ) p;

我进行了某些更改,使其与MySQL处理变量的方式更加一致。特别是SELECT DISTINCTORDER BY在子查询中。这在更新的MySQL版本中是必需的(尽管在最新版本中,您可以使用窗口函数)。

现在可以使用JOIN将其合并到更新中:

UPDATE PCount p JOIN
       (SELECT `G1%`, 
                (1 - ranks / totals) * 100 as Percentile
        FROM (SELECT `G1%`,
                      (@rank := @rank + 1) ranks,
                      (SELECT COUNT(*) FROM PCount) as totals
              FROM (SELECT DISTINCT `G1%`
                    FROM PCount
                    ORDER BY `G1%` DESC
                   ) p CROSS JOIN
                   (SELECT COUNT(*) as totals, @rank := 0
                    FROM Pcount
                   ) params
             ) pp
       ) pp
       ON pp.`G1%` = p.`G1%`
    SET p.G1Ptile = pp.percentile;