是否可以获取组中前 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/