2

我有一个具有以下布局的表格:

CREATE TABLE uploads ( 
    id      INTEGER     PRIMARY KEY AUTOINCREMENT
                        NOT NULL,
    user    CHAR( 32 )  NOT NULL,
    score   INTEGER     NOT NULL,
);

我正在尝试计算每个用户最近 10 个分数的平均值。

我已经尝试了许多不同的 SQL 查询,所有这些查询似乎都没有接近工作,所以我不会在这里粘贴它们中的任何一个:(

以下查询适用于获取单个用户的平均值,但我无法按用户列分组或基于用户字段执行相关子查询。

select avg(score) from (select score from upload where user="TEST" order by id limit 10)

4

1 回答 1

2

我不肯定这在 SQLite 中有效,但这是获得此结果的标准 SQL 方式:

select u.*
       (select avg(score*1.0) from (select * from uploads u2 where u2.user = u.user order by id desc limit 10)) as avg10
from uploads u

德姆斯提出了一个很好的观点。要为每个用户获取一行,您可以执行以下操作:

select u.user,
       (select avg(score*1.0) from (select * uploads u2 where u2.user = u.user order by id desc limit 10) t) as avg10
from (select distinct user
      from uploads
     ) u

我将 distinct 放在子查询中,因此 SELECT 中的子查询不会被评估太多次。用户表也是一个好主意,而不是子查询。

于 2012-09-06T20:43:52.020 回答