3

我有一个包含以下列的表格:

dayoftheweek (VARCHAR)
player (VARCHAR)
score (INT)

对于每个玩家,有 3、4 或 5 个分数。我必须计算每周每一天每个玩家最好的 3 个得分的平均值。

我在想

SELECT dayoftheweek, player, (SUM(score) / 3) AS average_score
FROM (SELECT dayoftheweek, player, score
      FROM scoretable
      GROUP BY dayoftheweek, player
      ORDER BY score
      LIMIT 0, 3) AS query

但是(显然)这只给了我前三条记录。有人能把我引向正确的方向吗?

干杯,马塞尔

4

1 回答 1

2

你应该能够写:

SELECT dayoftheweek,
       player,
       ( SELECT AVG(score)
           FROM ( SELECT inner.score
                    FROM scoretable AS inner
                   WHERE inner.dayoftheweek = outer.dayoftheweek
                    AND inner.player = outer.player
                   ORDER
                      BY inner.score DESC
                   LIMIT 3
                )
       ) AS best_score_avg
  FROM scoretable AS outer
;

(免责声明:未经测试。)

请注意,我曾经ORDER BY ... DESC获得三个最高分数,但如果这些是高尔夫分数或最好分数是最低分数的东西,那么您将要更改DESCASC(或将其删除)。

于 2013-03-09T07:46:26.490 回答