如何进行SQL查询排名?

时间:2011-05-18 22:58:47

标签: mysql sql subquery

考虑到最佳时间和分数,如何获得有史以来最好的排名?假设用户赢了几次,如何计算最佳用户获胜次数以及获胜的平均时间是多少?

+----------------+----------------+--------+-----------------------+
| user_id        | quiz_id        | score  | finish                |
+----------------+----------------+--------+-----------------------+
| 1              | 1              | 1      | 2011-05-18 21:39:00   |
| 2              | 1              | 1      | 2011-05-18 21:43:10   |
| 3              | 1              | 0      | 2011-05-18 21:40:55   |
| 1              | 2              | 1      | 2011-05-18 22:51:57   |
| 2              | 2              | 1      | 2011-05-18 22:21:37   |
| 3              | 2              | 0      | 2011-05-18 22:22:48   |
| 4              | 2              | 1      | 2011-05-18 22:58:14   |              
+----------------+----------------+--------+-----------------------+

1 个答案:

答案 0 :(得分:1)

考虑到最新的完成日期时间,获得最佳分数非常容易。

<强>总体

SELECT user_id, quiz_id, score, finish
FROM table
ORDER BY score DESC, finish DESC
LIMIT 1

每次测验

SELECT user_id, quiz_id, score, finish
FROM table
GROUP BY quiz_id
ORDER BY score DESC, finish DESC

适用于每位用户

SELECT user_id, quiz_id, score, finish
FROM table
GROUP BY user_id
ORDER BY score DESC, finish DESC

我不确定你的用户获胜次数是什么意思。什么意味着胜利?与平均时间相同;这里没有足够的信息来帮助你解决这两个问题。