sql 多条件排序并去重(已解决)

原问题

遇到的问题,有一张用户成绩表。

字段为:主键id,用户id,分数,创建时间,其他字段。

用户id会重复。

需要对用户成绩进行排序,排序规则是分数降序,时间升序。

并且每个用户只会出现一次(去重),取分数最高时间最早的那条。

解决方案

~~~sql
SELECT s.user_id, s.score, s.create_time
FROM user_score s
         INNER JOIN (SELECT user_id, chart_id, MAX(score) AS max_score
                     FROM user_score
                     WHERE chart_id = 11
                     GROUP BY user_id, chart_id) t
                    ON s.user_id = t.user_id AND s.chart_id = t.chart_id AND s.score = t.max_score
         inner join(select user_id, chart_id, max(create_time) as time
                    from user_score
                    where chart_id = 11
                    group by user_id, chart_id) u
                   on s.user_id = u.user_id AND s.chart_id = u.chart_id AND s.create_time = u.time
WHERE s.chart_id = 11
ORDER BY s.score DESC, s.create_time DESC
LIMIT 50;
~~~

详细解决过程可以看我的博客,其实sql算是ChatGPT写出来的

https://cooooing.github.io/%E7%BC%96%E7%A8%8B%E8%AE%B0%E5%BD%95/sql%E5%A4%9A%E6%9D%A1%E4%BB%B6%E6%8E%92%E5%BA%8F%E5%B9%B6%E5%8E%BB%E9%87%8D/