Oscar Muñoz
Oscar Muñoz

Reputation: 439

Get the average of the first’s N elements in a query LARAVEL

I’m stuck in silly thing but don’t know how to do it, whenever I want to get the average of a column without retrieving all the data from de database I just run the following code:

Result::where('test_id', $test->id)->avg('grade')

The answer for a particular example is 37, now when I want to get the first 10 rows, I will run this:

Result::select('grade')->where('test_id', $test->id)
       ->orderBy('grade', 'asc')->limit(10)->get();

This off course will give me the first 10 rows, and if I use a calculator and get the average of the grades I will get 33, but if I run the following I:

Result::where('test_id', $test->id)->orderBy('grade','asc')->limit(10)->avg('grade');

I get the same 37 as with the total dataset. I'm pretty sure it is a silly thing but I can’t figure out what it is.

Upvotes: 3

Views: 1006

Answers (1)

Don't Panic
Don't Panic

Reputation: 41820

I'm kind of guessing, because I'm not set up to test this right now, but what I'm thinking is, you're using the builder avg method, which does an SQL aggregate function, and the limit(10) is being applied after the aggregation has already happened and there's only one row anyway.

I think if you do avg after you get the limited results, then you'll be using the collection avg method instead, and averaging over the 10 rows the query returned.

Result::where('test_id', $test->id)
        ->orderBy('grade','asc')->limit(10)->get()->avg('grade');

Upvotes: 2

Related Questions