0

我被困在 Postgres 中的一个查询上,并且非常沮丧。我有一个名为 scores 的表,包含三列:

score, user_id and date

我想得到所有用户最后 5 分的平均值。这个查询并不完全让我明白:

SELECT user_id, 
       ROUND( AVG( score )::numeric, 2) as sc_avg
FROM 
(SELECT ROW_NUMBER() OVER (PARTITION BY user_id) AS r,
    sc.*
    from mg.scores sc
WHERE score IS NOT NULL
ORDER BY date DESC) AS x
WHERE x.r >= 5
GROUP BY user_id;

有没有更好的方法来限制每个用户的最后 5 个作业?

4

1 回答 1

1

正如 a_horse 评论的那样,该ORDER BY子句必须进入窗口函数。
而且由于您的订单是descending,因此它需要是<=而不是>=

SELECT user_id, round(avg(score)::numeric, 2) AS sc_avg
FROM  (
   SELECT *
        , row_number() OVER (PARTITION BY user_id ORDER BY date DESC) AS rn
   FROM   mg.scores
   WHERE  score IS NOT NULL
   ) AS x
WHERE  x.rn <= 5
GROUP  BY user_id;

如果date可以NULL,请使用ORDER BY date DESC NULLS LAST. 看:

于 2013-11-11T11:11:40.063 回答