我一直在想办法根据两个值来分配等级。我的桌子如下:

---------------------------------------
| 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 |
---------------------------------------

等级值是通过划分错误/任务来计算的,因此我可以知道最好的学生,但是,John和Ria的等级相同,但是John是更好的学生,因为他比Ria做的任务更多,所以我需要给他分配等级1-Ria将是等级2-Piccolo等级3-goku等级4和Vegeta等级5。
我试过了
SELECT * from students ORDER BY Task DESC, Errors ASC

但只按Task排序,似乎忽略了第二个值,按rank排序是可以的,但是我如何分配正确的顺序呢?
要分配的新rank应基于最大任务数与最小错误数,因此任务多而错误少的学生应排在第1位,以此类推。

最佳答案

试试这个;

select t.*, @r := @r + 1 as `new_rank`
from  tbl t,
(select @r := 0) r
order by `Rank` asc, `Tasks` desc

演示sqlfiddle
如果没有rankErrors/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

sqlfiddle
如果你只想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

sqlfiddle

10-06 05:50