在MYSQL中有效分配百分位数/等级

时间:2011-08-17 00:35:58

标签: mysql sql database rank

我有几张非常大的表(超过400,000行),如下所示:

+---------+--------+---------------+
| ID      | M1     | M1_Percentile |
+---------+--------+---------------+
| 3684514 | 3.2997 | NULL          |
| 3684515 | 3.0476 | NULL          |
| 3684516 | 2.6499 | NULL          |
| 3684517 | 0.3585 | NULL          |
| 3684518 | 1.6919 | NULL          |
| 3684519 | 2.8515 | NULL          |
| 3684520 | 4.0728 | NULL          |
| 3684521 | 4.0224 | NULL          |
| 3684522 | 5.8207 | NULL          |
| 3684523 | 6.8291 | NULL          |
+---------+--------+---------------+...about 400,000 more

我需要为M1_Percentile列中的每一行指定一个值,该值表示“M1值等于或低于当前行的M1值的行的百分比”

换句话说,我需要:

enter image description here

我实现了这个成功,但是FAR FAR太慢了。如果有人能够创建以下代码的更高效版本,我将非常感激!

UPDATE myTable AS X JOIN (
SELECT
  s1.ID, COUNT(s2.ID)/ (SELECT COUNT(*) FROM myTable) * 100 AS percentile
FROM
  myTable s1 JOIN myTable s2 on (s2.M1 <= s1.M1)
GROUP BY s1.ID
ORDER BY s1.ID) AS Z 
ON (X.ID = Z.ID) 
SET X.M1_Percentile = Z.percentile;

如果行数限制为您看到的行数(10行),则这是上述查询的(正确但缓慢)结果:

+---------+--------+---------------+
| ID      | M1     | M1_Percentile |
+---------+--------+---------------+
| 3684514 | 3.2997 |            60 |
| 3684515 | 3.0476 |            50 |
| 3684516 | 2.6499 |            30 |
| 3684517 | 0.3585 |            10 |
| 3684518 | 1.6919 |            20 |
| 3684519 | 2.8515 |            40 |
| 3684520 | 4.0728 |            80 |
| 3684521 | 4.0224 |            70 |
| 3684522 | 5.8207 |            90 |
| 3684523 | 6.8291 |           100 |
+---------+--------+---------------+

为整个400,000行生成相同的结果需要更长的时间。

2 个答案:

答案 0 :(得分:3)

我不能测试这个,但你可以试试像:

update table t
set mi_percentile = (
    select count(*)
    from table t1
    where M1 < t.M1 / (
        select count(*)
        from table));

更新:

update test t
set m1_pc = (
    (select count(*) from test t1 where t1.M1 < t.M1) * 100 /
    ( select count(*) from test));

这适用于Oracle(我唯一可用的数据库)。我记得在MySQL中得到了这个错误。这很烦人。

答案 1 :(得分:1)

公平警告:mysql不是我的原生环境。但是,经过一番研究后,我认为以下查询应该可行:

UPDATE myTable AS X 
JOIN ( 
  SELECT  X.ID, (
      SELECT  COUNT(*)
      FROM    myTable X1
      WHERE   (X.M1, X.id) >= (X1.M1, X1.id) as Rank)
  FROM myTable as X
) AS RowRank
ON (X.ID = RowRank.ID)
CROSS JOIN (
  SELECT COUNT(*) as TotalCount 
  FROM myTable 
) AS TotalCount
SET X.M1_Percentile = RowRank.Rank / TotalCount.TotalCount;