Laravel 5查询计数和分组

时间:2016-03-13 10:22:52

标签: mysql laravel-5

我的报告生成需要一些帮助。

我的表结构如下:

flight_no  year  month ....  ...

402        2016    1
402        2016    1
403        2016    1
402        2016    2
403        2016    2
403        2016    2
403        2016    3

我希望按月计算一个年度报告组,并计算每个月的航班数和航班号。我在laravel做这个。

我试过了:

$total_scheduled = DB::table('schedule_details')
                            ->select('id','flight_id','year','month' 
                                    DB::raw('count(id) as total_sch')
                              )
                            ->where('year','2016')
                            ->groupBy('month')
                            ->get();

它给了我总的航班,但我很困惑地获得每个月的所有航班号,例如:

  

第1个月   total_sc = 3
  航班号码= 402,403

     

月2日   total_sc = 3
  航班号码= 402,403

     

月3日   total_sc = 1
  航班号= 403

1 个答案:

答案 0 :(得分:0)

我可以通过以下方式解决这个问题,但我需要在一个查询中这可能吗?

$month_schs = ScheduleDetail::where('year','2016')
                                    ->groupBy('month')->get(['year', 'month']);

  foreach($month_schs as $month_sch){

     echo '<b>'.$month_sch->year.'-'.$month_sch->month.'</b><br>';

     $flight_nos = ScheduleDetail::where('year',$month_sch->year)
                                ->where('month',$month_sch->month)
                                ->groupBy('flight_number')
                                ->get(['flight_number']);



        foreach($flight_nos as $flight_no){

                  echo '<b>'.$flight_no->flight_number.'</b><br>';


        }

}
相关问题