MySQL按百分比排名计算得分

时间:2013-04-23 14:54:22

标签: mysql

我正在使用MYSQL创建一个评级系统来实现我的数据库。我想要做的是通过一些计算对每个属性的百分比进行评级。以下是示例数据库:

| ID | VALUE1 | VALUE2| 
-----------------------
|  2 |      5 |    20 | 
|  4 |      5 |    30 | 
|  1 |      3 |     5 | 
|  3 |      2 |     8 |

这是我需要的理想输出:

| ID | VALUE1 | RANK1 | Score1 | VALUE2 | RANK2 | Score2 |
---------------------------------------------------------
|  2 |      5 |     1 |     10 |     20 |      2|     8.3|
|  4 |      5 |     1 |     10 |     30 |      1|      10|
|  1 |      3 |     2 |     7.5|      5 |      4|       5|
|  3 |      2 |     3 |      5 |      8 |      3|     6.6|

分数计算公式为

5+5*(MaxRank-rank)/(MaxRank-MinRank)

如何生成像表一样的多个排名?我试过了

SELECT
    @min_rank := 1 AS min_rank
  , @max_rank1 := (SELECT COUNT(DISTINCT value1) FROM table) AS max_rank1
  , @max_rank2 := (SELECT COUNT(DISTINCT value2) FROM table) AS max_rank2
  ;
SELECT
    ID
  , R1
  , TRUNCATE(5.0+5.0 * (@max_rank1 - R1) / (@max_rank1 - @min_rank), 2) AS Score1
  , R2
  , TRUNCATE(5.0+5.0 * (@max_rank2 - R2) / (@max_rank2 - @min_rank), 2) AS Score2
FROM (
  SELECT
      ID
    , value1
    , FIND_IN_SET( `value1`, (SELECT GROUP_CONCAT(DISTINCT `value1` ORDER BY `value1` DESC) FROM table)) AS R1
    , value2
    , FIND_IN_SET( `value2`, (SELECT GROUP_CONCAT(DISTINCT `value2` ORDER BY `value2` DESC) FROM table)) AS R2
  FROM table
) ranked_table;

它的排名低于170可以正常工作。我的数据库对于某些值有大约200+的排名,而大于170的排名将在返回时被视为0。在这种情况下,排名> 170的分数将被错误计算。谢谢你们。

1 个答案:

答案 0 :(得分:0)

这看起来很讨厌。

这样的事可能会这样做

SELECT a.ID, a.VALUE1, Sub1.Rank1, (5.0+5.0 * (Sub3.MaxRank1 - Sub1.Rank1) / (Sub3.MaxRank1 - 1)) AS Score1, a.VALUE2, Sub2.Rank2, (5.0+5.0 * (Sub4.MaxRank2 - Sub2.Rank2) / (Sub4.MaxRank2 - 1)) AS Score2
FROM TestTable a
INNER JOIN (SELECT DISTINCT z.VALUE1, (SELECT ((COUNT(DISTINCT VALUE1) + 1)) FROM TestTable y WHERE z.VALUE1 < y.VALUE1)  AS RANK1
FROM TestTable z
) Sub1 ON a.VALUE1 = Sub1.VALUE1
INNER JOIN (SELECT DISTINCT z.VALUE2, (SELECT ((COUNT(DISTINCT VALUE2) + 1)) FROM TestTable y WHERE z.VALUE2 < y.VALUE2)  AS RANK2
FROM TestTable z
) Sub2 ON a.VALUE2 = Sub2.VALUE2
CROSS JOIN (SELECT COUNT(*) + 1 AS MaxRank1 FROM TestTable CROSS JOIN (SELECT MAX(VALUE1) AS MaxValue1 FROM TestTable) Sub3a WHERE VALUE1 < MaxValue1) Sub3
CROSS JOIN (SELECT COUNT(*) + 1 AS MaxRank2 FROM TestTable CROSS JOIN (SELECT MAX(VALUE2) AS MaxValue2 FROM TestTable) Sub4a WHERE VALUE2 < MaxValue2) Sub4

注意我不确定你的分数计算。您给出的等式在我看来不会在您的示例中给出结果。但我可能会误读它。