I have a table in my database as shown below:
id | date | amount
========================
1 | 2015-01-26 | 1000
2 | 2015-02-26 | 100
3 | 2014-06-26 | 10
I want to group the records by year and then find the sum of the amount of each group.
I can find the groups using the following query:
Fee::orderBy('date', 'DESC')
->get()
->groupBy(function($date) {
return Carbon::parse($date->date)->format('Y'); // grouping by years
})
But I am not able to get the sum of amount of each group.
Afraid I can't figure it out right now with eloquent, this should work for the query builder though. It's working okay for me:
DB::table('fees')
->select(DB::raw('YEAR(date) as year'), DB::raw('sum(amount) as total'))
->groupBy(DB::raw('YEAR(date)') )
->get();
Using the same date you put in the question:
id date amount
1 2015-01-26 1000
2 2015-02-26 100
3 2014-06-26 10
And it gives the following:
array:2 [▼
0 => {#150 ▼
+"year": 2014
+"total": "10"
}
1 => {#151 ▼
+"year": 2015
+"total": "1100"
}
]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.