ruby on rails - How to get recent n items average by ActiveRecord -
there company
has many dailydatum
. dailydatum
has date
, volume
columns.
class company < activerecord::base has_many :daily_data end
i want average of recent 10 volumes
. code got average value.(i implemented array#mean
method)
company = company.first company.daily_data.order(date: :desc).limit(10).pluck(:volume).mean
and thought it's more efficiant if use postgresql
avg
function. somehow order
ignored this.
company.daily_data.order(date: :desc).limit(10).average(:volume) (15.7ms) select avg("daily_data"."volume") "daily_data" "daily_data"."company_id" = $1 limit 10 [["company_id", 1123]]
can use limit
, order
, average
@ same time?
you need use sub-query queries that
select avg(volume) (select volume daily_data company_id = 1 limit 10) temp
doing in rails include find_by_sql
method. don't think notice performance benefit this, since you're calculating 10 records.
Comments
Post a Comment