Summation query using groupBy() function in laravel

荒凉一梦 提交于 2019-12-02 12:52:16

Assuming your table name is transactions, and the columns and data like in your sample table - The SQL query would be

SELECT Name, SUM(Amount) as Amount, Date
FROM transactions
GROUP BY Name, Date

In laravel you would write it as

$data = DB::table('transactions')                
    ->select('Name', DB::raw('SUM(Amount) as Amount'), 'Date')
    ->groupBy('Name', 'Date')
    ->get();

You can add your WHERE conditions and what ever you need to the query. But if you need to select more columns from the table, you will also need to add them to the groupBy() clause. Something like transactions.* will probably not work due to ONLY_FULL_GROUP_BY mode. But it also probably doesn't make sense.

You can use SUM(Amount) with groupBy(date)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!