按多列的最高平均排名排序

时间:2014-05-26 07:23:25

标签: mysql sql

我处在棘手的情况下,我需要在一个表中按三列中的最高位置排序。

例如,这是一个基本表;

ID  Stat1   Stat2   Stat3
--------------------------
1   400     100     200
2   200     200     100
3   100     400     400
4   300     300     300

理想情况下,每行将按其在每列中的平均位置排序,按最低升序排序。这是理想情况下返回的内容:

ID  Average
------------
3   2
4   2
2   2.3333333333333
1   2.6666666666667

第一个ID获得最低位置,因为对于第一个,第二个和第三个统计数据,它排名为1 4和3,这是2.6666666666667.的平均值

1 个答案:

答案 0 :(得分:7)

这个怎么样?

SELECT id, (rank_by_stat1 + rank_by_stat2 + rank_by_stat3) / 3 AS avg
FROM (
    SELECT id, @rank_by_stat1 := @rank_by_stat1 + 1 AS rank_by_stat1
    FROM test, (SELECT @rank_by_stat1 := 0) init
    ORDER BY stat1 DESC
) stat1 INNER JOIN (
    SELECT id, @rank_by_stat2 := @rank_by_stat2 + 1 AS rank_by_stat2
    FROM test, (SELECT @rank_by_stat2 := 0) init
    ORDER BY stat2 DESC
) stat2 USING(id) INNER JOIN (
    SELECT id, @rank_by_stat3 := @rank_by_stat3 + 1 AS rank_by_stat3
    FROM test, (SELECT @rank_by_stat3 := 0) init
    ORDER BY stat3 DESC
) stat3 USING(id)
ORDER BY avg;
+------+--------------------+
| id   | avg                |
+------+--------------------+
|    3 |                  2 |
|    4 |                  2 |
|    1 | 2.6666666666666665 |
|    2 | 3.3333333333333335 |
+------+--------------------+
4 rows in set (0.00 sec)

工作原理

这很简单。我修改了变量名来自我解释。查看大多数内部查询之一的输出会很有帮助:

SELECT id, @rank_by_stat1 := @rank_by_stat1 + 1 AS rank_by_stat1, stat1
FROM test, (SELECT @rank_by_stat1 := 0) init
ORDER BY stat1 DESC
+------+---------------+-------+
| id   | rank_by_stat1 | stat1 |
+------+---------------+-------+
|    1 |             1 |   400 |
|    4 |             2 |   300 |
|    2 |             3 |   200 |
|    3 |             4 |   100 |
+------+---------------+-------+