Laravel SQL groupBy And Sum

时间:2016-05-31 15:54:51

标签: php mysql laravel laravel-5

这是我的表关系:

**reservations** id, date, etc...<br>
**reservation_service_info** service_info_id, reservation_id<br>
**services_info** price etc...

我想把白天的预订价格加起来。这是代码和结果:

return $query->selectRaw('DATE(start_time) AS date')
        ->selectRaw("(SELECT SUM(price) FROM `services_info` inner join `reservation_service_info` on `services_info`.`id` = `reservation_service_info`.`service_info_id` where `reservation_service_info`.`reservation_id` = reservations.id) as price")
        ->orderBy('date', 'ASC')
        ->get('price', 'date')

结果:

[
  {
    "date": "2016-06-01",
    "price": "345.00"
  },
  {
    "date": "2016-06-01",
    "price": "90.00"
  },
  {
    "date": "2016-06-01",
    "price": "222.00"
  },
  {
    "date": "2016-06-02",
    "price": "393.00"
  },
  {
    "date": "2016-06-02",
    "price": "142.00"
  }
]

当我在查询中添加groupBy('date')时,它按剂量SUM(价格)

进行分组
[
  {
    "date": "2016-06-01",
    "price": "345.00"
  },
  {
    "date": "2016-06-02",
    "price": "393.00"
  }
]

3 个答案:

答案 0 :(得分:1)

我认为你的查询是以错误的方式构建的。我会建议这种思维方式:

return $query->select(\DB::raw('DATE(start_time) AS date'), \DB::raw('SUM(price) as price'))
        ->join('reservation_service_info', 'reservations.id', '=', 'reservation_service_info.reservation_id')
        ->join('services_info', 'services_info.id', '=', 'reservation_service_info.services_info_id')
        ->orderBy('date', 'ASC')
        ->groupBy('date')
        ->get();

如果$query表格为reservations,这应该有用。

答案 1 :(得分:1)

试试这个:

                 $users=   DB::table('reservation_service_info')
                     ->join('services_info', 'reservation_service_info.service_info_id', '=', 'services_info.id')
                     ->join('reservations', 'reservation_service_info.reservation_id', '=', 'reservations.id')
                     ->select('DATE(reservations.start_time) AS date','SUM(services_info.price) AS price')
                     ->orderBy('reservations.start_time', 'ASC')
                     ->groupBy('reservations.start_time')
                     ->get();

答案 2 :(得分:0)

您应该使用sum(price)来获得总和:

return $query->selectRaw('DATE(start_time) AS date')
        ->selectRaw("(SELECT SUM(price) FROM `services_info` inner join `reservation_service_info` on `services_info`.`id` = `reservation_service_info`.`service_info_id` where `reservation_service_info`.`reservation_id` = reservations.id) as price")
        ->orderBy('date', 'ASC')
        ->groupBy('date')
        ->get();