我试图想出一种基于两个值来分配排名的方法。我的表格如下:
---------------------------------------
| id | Student | Tasks | Errors | Rank |
---------------------------------------
| 1 | Vegeta | 80 | 1500 | 18.7 |
---------------------------------------
| 2 | Ria | 100 | 150 | 1.5 |
---------------------------------------
| 3 | John | 200 | 300 | 1.5 |
---------------------------------------
| 4 | Goku | 24 | 100 | 4.16 |
---------------------------------------
| 5 | Piccolo | 80 | 148 | 1.85 |
---------------------------------------
排名值是根据错误/任务计算出来的,所以我可以了解最好的学生,但是,约翰和里亚有相同的等级,但约翰是一个更好的学生,因为他做了比Ria更多的任务,所以我需要指定他排名1 - ria将排名2 - Piccolo排名3 - 悟空排名4和Vegeta排名5.
我试过
SELECT * from students ORDER BY Task DESC, Errors ASC
但只按Task
对其进行排序,似乎忽略了第二个值,按rank
排序就可以,但是我可以如何分配正确的顺序?
要分配的新rank
应基于任务Vs的最大数量。最小错误数,因此具有更多任务和更少错误的学生应该在等级1上,依此类推。
答案 0 :(得分:1)
在 ORDER BY
中使用您的计算SELECT * from students
ORDER BY (Errors / Task), Task DESC;
<强>结果:强>
MariaDB [test]> select * from students;
+----+---------+------+--------+------+
| id | Student | Task | Errors | Rank |
+----+---------+------+--------+------+
| 1 | Vegeta | 80 | 1500 | 18.7 |
| 2 | Ria | 100 | 150 | 1.5 |
| 3 | John | 200 | 300 | 1.5 |
| 4 | Goku | 24 | 100 | 4.16 |
| 5 | Piccolo | 80 | 148 | 1.85 |
+----+---------+------+--------+------+
5 rows in set (0.00 sec)
MariaDB [test]>
MariaDB [test]> SELECT * FROM students
-> ORDER BY (ERRORS / Task), Task DESC;
+----+---------+------+--------+------+
| id | Student | Task | Errors | Rank |
+----+---------+------+--------+------+
| 3 | John | 200 | 300 | 1.5 |
| 2 | Ria | 100 | 150 | 1.5 |
| 5 | Piccolo | 80 | 148 | 1.85 |
| 4 | Goku | 24 | 100 | 4.16 |
| 1 | Vegeta | 80 | 1500 | 18.7 |
+----+---------+------+--------+------+
5 rows in set (0.00 sec)
MariaDB [test]>
答案 1 :(得分:1)
试试这个;
select t.*, @r := @r + 1 as `new_rank`
from tbl t,
(select @r := 0) r
order by `Rank` asc, `Tasks` desc
演示 sqlfiddle
如果你没有,那么就有rank
(Errors
/ Tasks
)列;
select
`id`, `Student`, `Tasks`, `Errors`,
@r := @r + 1 as `rank`
from tbl t,
(select @r := 0) r
order by (`Errors` / `Tasks`) asc, `Tasks` desc
如果您只想order
您的结果;
order by `Rank` asc, `Tasks` desc
的
order by (`Errors` / `Tasks`) asc, `Tasks` desc
修改强> 如果新用户只有20个任务且0个错误?
select t.*, @r := @r + 1 as `new_rank`
from tbl t,
(select @r := 0) r
order by
case when `rank` = 0 then 0 else 1 end desc,
`Rank` asc, `Tasks` desc