2016-12-13 47 views
1

我有一個Laravel應用程序。我正在計算列和平衡的總和。你能幫我寫一下這個SQL嗎?Laravel - SUM和balane查詢

+---------+----------+--------+----------+----------+------------+ 
| pay_id | username | income | outgoings| balance |  date | 
+---------+----------+--------+----------+----------+------------+ 
| 1 | john | 1000 |   | 1000 | 00.00.2016 | 
| 2 | jack |  | 500 | 500 | 00.00.2016 | 
| 3 | john | 1500 |   | 2000 | 00.00.2016 | 
| 4 | bill |  | 1000 | 1000 | 00.00.2016 | 
+---------+----------+--------+----------+----------+------------+ 
         2500  1500   
+0

你嘗試過什麼嗎?另外,目前還不清楚您是否在尋找獲得計算「平衡」列的方法,或者您是否想要「收入」和「支出」列的逐行總和。 –

+0

我什麼都沒試過。我不知道從哪裏開始 – Selim

回答

0

如果要總結多個列,那麼你必須給我們DB::raw

$data = Model::get([ 
     DB::raw('SUM(income) AS total_income'), 
     DB::raw('SUM(outgoings) AS total_outgoings'), 
     DB::raw('SUM(balance) AS total_balance') 
    ]); 
dd($data); 

或者

$data = Model::select(
     DB::raw('SUM(income) AS total_income'), 
     DB::raw('SUM(outgoings) AS total_outgoings'), 
     DB::raw('SUM(balance) AS total_balance') 
    ) 
    ->get(); 
dd($data);