mysql根据得分和最短时间获得用户排名

时间:2017-10-19 15:27:22

标签: php mysql

我有这样的表:

+-------------+---------------------+---------------------+--------+
| id  | name  |       start_time    |        end_time     | score  |
+-------------+---------------------+---------------------+--------+
| 1   | Jon   | 2017-10-19 01:00:00 | 2017-10-19 01:20:00 |  20    |
| 2   | Jane  | 2017-10-19 01:15:00 | 2017-10-19 01:30:00 |  20    |
| 3   | Fred  | 2017-10-19 01:00:25 | 2017-10-19 03:10:35 |  80    |
| 4   | July  | 2017-10-19 01:12:28 | 2017-10-19 01:16:35 |  10    |
+-------------+---------------------+---------------------+--------+

我想要这个:

+-------------+---------------------+---------------------+--------+-------+
| id  | name  |       start_time    |        end_time     | score  |  rank |
+-------------+---------------------+---------------------+--------+-------+
| 3   | Fred  | 2017-10-19 01:00:25 | 2017-10-19 03:10:35 |  80    |   1   |
| 2   | Jane  | 2017-10-19 01:15:00 | 2017-10-19 01:30:00 |  20    |   2   |
| 1   | Jon   | 2017-10-19 01:00:00 | 2017-10-19 01:20:00 |  20    |   3   |
| 4   | July  | 2017-10-19 01:12:28 | 2017-10-19 01:16:35 |  10    |   4   |
+-------------+---------------------+---------------------+--------+-------+

基本上,我想按分数排序。如果分数相等,则按最低持续时间时间排序。 这与仅按分数排序不同,它还应该从start_time和end_timer计算持续时间

1 个答案:

答案 0 :(得分:0)

DEMO:

  1. 可以使用用户变量来模拟row_number以给我们排名。
  2. 获取持续时间差异只需减去时间。结束 - 开始
  3. 然后我们可以按分数降序和持续时间升序排序。
  4. SELECT A.*, @RN:=@RN+1 as Rank
    FROM SO46833505_TBL  A
    CROSS JOIN  (Select @RN:=0) Z
    ORDER BY  score desc, end_time-Start_Time asc;