Split sum and Count output in the same Query?

Asked

Viewed 248 times

2

The code below works, but I wanted to know how to do it all query, and if the way I’m riding her is really the best way.

$query = Avaliar::select(DB::raw('COUNT(id) as contar'), DB::raw('SUM(nota) as total'))
        ->where('serie_id', $serie->id)
        ->first();

$nota = $query->total / $query->contar;

1 answer

2


Could make the split in the SQL as follows, example:

$query = Avaliar::select(DB::raw('(SUM(nota) / COUNT(id)) as nota'))
        ->where('serie_id', $serie->id)
        ->first();

$nota = $query->nota;

now, your and this answer come to the same purpose, so everything will depend on where it will be used, because depending on the rule one of the two without fitting.

References

Browser other questions tagged

You are not signed in. Login or sign up in order to post.