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

android - Why am I getting the message 'Youractivity.java is not an activity subclass or alias' -

Making Empty C++ Project: General exception (Exception from HRESULT:0x80131500) Visual Studio Community 2015 -

How to fix java warning for "The value of the local variable is not used " -