sqlite:获取每个项目的前 X% 的平均值

标签 sql sqlite aggregate-functions

是否可以获取组中前 X% 项目的平均值?

例如:
我有一个表,其中包含 item_id、时间戳和价格列。输出应按 item_id 和时间戳分组,并且“价格列”应取平均值。对于平均值,应仅使用该组中的最低 X% 价格。

我发现了类似的问题 ( How to select top x records for every group ) 但这不适用于 sqlite。

最佳答案

获取每个组内的前 n 条记录需要计数。假设没有重复项,以下查询返回某项的记录数:

select t.*,
       (select count(*) from t t2 where t2.item_id = t.item_id
       ) as NumPrices
from t

这称为相关子查询。现在,让我们扩展这个想法以包括排名,然后计算正确组的平均值:

select item_id, avg(price)
from (select t.*,
             (select count(*) from t t2 where t2.item_id = t.item_id
             ) as NumPrices,
             (select count(*) from t t2 where t2.item_id = t.item_id and t2.price <= t.price
             ) as PriceRank
      from t
     ) t
where (100.0*PriceRank / NumPrices) <= X
group by item_id

为了提高性能,您需要在 (item_id, price) 上建立索引。

关于sqlite:获取每个项目的前 X% 的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15878160/

相关文章:

sql - SQL 中外连接的目的(或用例)是什么?

sql - 通过Oracle SQL查询将行中以逗号分隔的值拆分为一列

android - 将 sqlite 查询打印到 logCat

mysql - 没有分组依据的聚合列

MySQL 在没有 GROUP BY 子句的情况下中断

MySQL 比较、计数和排序

sql - Laravel 查询生成器输出测试

ruby-on-rails - Heroku 尝试在每次部署时安装 sqlite

java - SQLiteDatabaseHelper接收IllegalStateException : database not open in constructor

linq-to-sql - 使用连接和聚合函数的 LINQ 查询