Laravel查询生成器与总和

时间:2017-05-12 08:44:59

标签: mysql laravel-5 sum

下面是查询,我有这个错误

SQLSTATE [42000]:语法错误或访问冲突:1064 SQL语法错误

        $games = DB::table('games')
        ->select('start','dayofweek','name','ins_id','location_id',
            DB::raw('SUM(reservations) as reservations'),
            DB::raw('SUM(reservationsmax) as reservationsmax'),
            DB::raw('SUM(entries) as entries'),
            DB::raw('SUM(entriesmax) as entriesmax'),
            DB::raw('(SUM(entries) / SUM(reservationsmax) * 100 as percentage'))
        ->where('club_id', $club_id)
        ->whereBetween('start', [$from, $to])
        ->where('hide_from_customers', 0)
        ->where('external_id', 0)
        ->orderBy('name')
        ->groupBy('start')
        ->groupBy('dayofweek')
        ->groupBy('name')
        ->get();

2 个答案:

答案 0 :(得分:1)

我找到了答案,我认为这对其他人也有帮助。

$games = \App\Models\Games::select(DB::raw('start,dayofweek,name,instructor_id,location_id,SUM(reservations) as reservations,SUM(reservationsmax) as reservationsmax,SUM(entries) as entries,SUM(entriesmax) as entriesmax,(SUM(entries) / SUM(reservationsmax)) * 100 as percentage'))
            ->where('club_id', $club_id)
            ->whereBetween('start', [$from, $to])
            ->where('hide_from_customers', 0)
            ->where('external_id', 0)
            ->orderBy('name')
            ->groupBy('start')
            ->groupBy('dayofweek')
            ->groupBy('name')
            ->get();

答案 1 :(得分:0)

  Something like this ....  

$games = DB::table('games')
    ->select(DB::raw('
        SUM(reservations) as reservations, 
        SUM(reservationsmax) as reservationsmax,
        SUM(reservationsmax) as reservationsmax,
        SUM(entries) as entries,
        SUM(entriesmax) as entriesmax,
        SUM(entries) / SUM(reservationsmax) * 100 as percentage'))
            ->where('club_id', $club_id)
                    ->whereBetween('start', [$from, $to])
                    ->where('hide_from_customers', 0)
                    ->where('external_id', 0)
                    ->orderBy('name')
                    ->groupBy('start')
                    ->groupBy('dayofweek')
                    ->groupBy('name')
                    ->get();