在 SQL 中进行平均和分组,但仅针对最佳 10 条记录

Average and group by in SQL but for best 10 records only

给出:一个排名table(id,user_id,分数,group_id,日期)

目前我们是根据所有参与用户的总和和平均值计算排名。

SELECT
    ROUND(AVG(r.score)::NUMERIC, 2) AS score,
    SUM(score) AS score_sum,
    MAX(r.date) AS ranking_timestamp,
    a.name AS group_name,
    a.id AS group_id
FROM
ranking r, group a
WHERE a.id = r.group_id
GROUP BY a.id,a.name
ORDER BY AVG(r.score) DESC,MAX(r.date) ASC

现在我们想改变它。不是尊重所有参与的用户,而是只取 10 个最好的用户,计算 SUM 和 AVG。

是否可以在一个语句中做到这一点?

添加TOP 10

SELECT TOP 10
    ROUND(AVG(r.score)::NUMERIC, 2) AS score,
    SUM(score) AS score_sum,
    MAX(r.date) AS ranking_timestamp,
    a.name AS group_name,
    a.id AS group_id
FROM
ranking r, group a
WHERE a.id = r.group_id
GROUP BY a.id,a.name
ORDER BY AVG(r.score) DESC,MAX(r.date) ASC

你可以这样做:

WITH TEMP AS
    (
        SELECT
            ROUND(AVG(r.score)::NUMERIC, 2) AS score,
            SUM(score) AS score_sum,
            MAX(r.date) AS ranking_timestamp,
            a.name AS group_name,
            a.id AS group_id
        FROM
        ranking r, group a
        WHERE a.id = r.group_id
        GROUP BY a.id,a.name
        ORDER BY AVG(r.score) DESC,MAX(r.date) ASC
    )


SELECT TOP 10 * FROM TEMP ORDER BY score ASC