2016-05-31 118 views
2

這裏是我的表關係:Laravel SQL GROUPBY,總結

**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" 
    } 
] 

當我在查詢這組是由dosent SUM(價格)加groupBy('date')

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

回答

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(); 
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(); 
+0

是的,我試過,但我得到同樣的效果,因爲這個選擇查詢只是選擇一列... – DokiCRO

+0

@ user3806764你可以編輯你的問題,並顯示期望的結果呢? –

+0

因爲我現在改變了。 – DokiCRO

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(); 

如果$queryreservations這應該工作。