21,891
社区成员
发帖
与我相关
我的任务
分享现在有个需求是这样的:用户可以参加多次练习模拟活动,每次模拟练习都会有一个分数和答题时间,现在要取每个用户最好成绩(分数最高,如果分数相同则比较用时最少)进行排名。
现在数据表如下
| id | userId | activityId | score | useTime |
| 1 | 1 | 12 | 78 | 32 |
| 2 | 1 | 12 | 78 | 40 |
| 3 | 1 | 12 | 80 | 33 |
| 4 | 2 | 12 | 76 | 33 |
| 5 | 2 | 12 | 90 | 25 |
| 6 | 2 | 12 | 88 | 20 |
| 7 | 3 | 12 | 80 | 45 |
| 8 | 3 | 12 | 92 | 38 |
| 9 | 3 | 12 | 76 | 22 |
有人知道这个SQL该怎么写吗?试了几次都没写出来,求SQL高手呀
select * from (
select userID,useTime,score,
row_number()over(partition by userID order by score desc,useTime asc) req
from test) t where t.req=1;
已经解决了,谢谢大家
SELECT a.*
FROM test AS a
RIGHT JOIN (SELECT userId,MAX(score) AS max_score FROM test GROUP BY userId) AS b ON a.userId = b.userId AND a.score = b.max_score
ORDER BY a.score DESC, a.useTime ASC;
按照你的字面意思就是这样的
select userID,max(score) from test group by userID;
可以用聚合函数max来取出最大分数和时间嘴短的数据进行排序就可以了