Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Dusted's avatar

How to get average of count column

Im getting the following error when i try to execute the code below.

 $dailyAverage = \DB::table('reviews')
            ->select(\DB::raw("to_char(date_trunc('day', created_at),'YYYY-MM-DD') as date, count(created_at)"))
            ->whereIn('location_id',$locationIds)
            ->groupBy('date')
            ->avg('count');

SQLSTATE[42703]: Undefined column: 7 ERROR: column "count" does not exist LINE 1: select avg("count") as aggregate from "reviews" where "locat... ^ (SQL: select avg("count") as aggregate from "reviews" where "location_id" in (1) group by "date")

0 likes
6 replies
martinbean's avatar

@Dusted Try aliasing the column, as you’re selected it ((`count(created_a) and that’s the name it’ll use.

 $dailyAverage = \DB::table('reviews')
            ->select(\DB::raw("to_char(date_trunc('day', created_at),'YYYY-MM-DD') as date, count(created_at) as count"))
            ->whereIn('location_id', $locationIds)
            ->groupBy('date')
            ->avg('count');
1 like
lquintana's avatar

Did anyone fix this problem. I am having the same situation and I can not figure it out :|

kevinbui's avatar

I think Martin's answer is close, but count is MySQL keyword, so its not accepted. Lets rename it to something else.

$dailyAverage = \DB::table('reviews')
            ->select(\DB::raw("to_char(date_trunc('day', created_at),'YYYY-MM-DD') as date, count(created_at) as     
            reviews_count"))
            ->whereIn('location_id', $locationIds)
            ->groupBy('date')
            ->avg('count');

Also, counting the created_at field is weird. I assume you want to count the number of reviews. So I rewrite it like this:

$dailyAverage = \DB::table('reviews')
            ->select(\DB::raw("to_char(date_trunc('day', created_at),'YYYY-MM-DD') as date, count(id) as     
            reviews_count"))
            ->whereIn('location_id', $locationIds)
            ->groupBy('date')
            ->avg('count');
t9dev's avatar

Now you can do find average and count using Eloquent, like this:

public function index()
    {
        $company = company::withAvg('rating as ratings', 'rating')
->withCount('comment as comments')
->latest()->filter()->paginate(12);
  
        return view('Company.Record.index', compact('company'));
    }

Please or to participate in this conversation.