2013-04-23 118 views
-1

我使用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的分數將被錯誤計算。感謝你們。

回答

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 

注意我不知道你的分數計算。你給出的等式在我看來並沒有在你的例子中給出結果。但我可能會誤解它。

+0

感謝您的幫助,但它會生成錯誤:1052.字段列表中的列「VALUE1」不明確。我已將它們更改爲數據庫中的名稱,但無法使用。 – ToddShih 2013-04-23 15:43:41

+0

有更多的玩法。這比我想象的要困難得多,我必須使用一些相關的子查詢,我試圖避免它們往往表現不佳。 – Kickstart 2013-04-23 16:20:11