SQL - 从每个表中选择最大值,按所述最大值排序,然后按created_at排序

时间:2017-07-27 11:03:05

标签: sql postgresql sqlite

SELECT id, author_id, max(result_score) as maxscore
FROM submissions
WHERE challenge_id = 10
GROUP BY author_id
ORDER BY maxscore DESC, created_at ASC

此查询获取每个作者的提交(一个),该提交具有最高分数并且最早创建。最后,我们应该最终得到有序的提交,每个作者一个,所有这些都是由maxscore和created_at命令

这在SQLite3中完美运行,但它无法在PostgreSQL上编译,因为它更严格。 PostgreSQL要求id通过group by子句或某种聚合函数使用。

我尝试了各种方法,使用DISTINCT ONHAVING,却无法使其发挥作用。这种查询是否可行,如果是,那么实现我想要的方法是什么?

2 个答案:

答案 0 :(得分:2)

它只能在SQLite中“完美”运行,因为SQLite已经破解。也就是说,它几乎在任何其他数据库中都会失败,因为它不是正确的SQL。

在Postgres中,您可以使用DISTINCT ON

执行您想要的操作
SELECT DISTINCT ON (author_id) id, author_id, result_score
FROM submissions
WHERE challenge_id = 10
ORDER BY author_id, result_score DESC, created_at ASC;

编辑:

如果您希望最终结果按result_score排序,则可以使用子查询:

SELECT s.*
FROM (SELECT DISTINCT ON (author_id) id, author_id, result_score
      FROM submissions
      WHERE challenge_id = 10
      ORDER BY author_id, result_score DESC, created_at ASC
     ) s
ORDER BY result_score DESC, created_at ASC;

答案 1 :(得分:2)

我设法使用像{/ p>这样的rank函数来解决这个问题

SELECT id, author_id, result_score
FROM (
    SELECT id, author_id, result_score, created_at,
           rank() OVER (PARTITION BY author_id ORDER BY result_score DESC, created_at ASC) AS rank
    FROM submission
    WHERE challenge_id = %s) as sub
WHERE sub.rank = 1
ORDER BY result_score DESC, created_at ASC