ruby on rails 3 - Bound activerecords-queries using aggregate funcs (sum, avg,...) with limit -


given pseudo-query:

model.sum(:column, :condition => ['id = ?', id], order => "date desc", :limit => x) 

here have problem sum obtained not "limited" value x (it takes sum values on column instead sum of x (firsts) entries).

it seems limit taken after calculating aggregate func sum.

how can sum limited firsts x entries?

murifox's suggestion doesn't work because limit applies final result set, has 1 row (the sum). see this thread.

the simplest way solve not count in database:

model.where(:id => id).order('date desc').limit(3).pluck(:column).compact.sum 

this loads values of column ruby , sums there. now, if set of records enormous, observably less efficient, because values getting loaded app's memory.

edit: added .compact - remove nils array before summing (which causes error).

the suggested method of doing in sql using subquery, so:

select sum(subquery.column) (   select * models id = 5 limit 3 ) subquery; 

there's not easy or straightforward way turn activerecord query, since expect selecting particular model's table.


Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -