Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

j_watson's avatar

Group query result by type and calculate sum of each group.

I have this query $data= DB::table('expenses') ->select('amount', 'type')->get(); now I want to group each expense by their type and calculate the sum of all the amount that have the same type. How do you think I should go about this?

0 likes
2 replies
DhPandya's avatar
DhPandya
Best Answer
Level 12

Using the below statement you can group by your results with type and also get the some of each types. $data= DB::table('expenses')->select([DB::raw('SUM(amount) as total_amount'), 'type'])->groupBy('type')->get();

Please or to participate in this conversation.