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

Viewed 847

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.

1 Answers
Related