Summation query using groupBy() function in laravel

前端 未结 2 1707
夕颜
夕颜 2021-01-27 11:47

A table where X, Y and Z have some individual amounts.

Sample data:

Name | Amount |  Date
—————|————————|—————————
  X  |    100 | 15-11-17
  Y  |     50         


        
相关标签:
2条回答
  • 2021-01-27 12:04

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

    0 讨论(0)
  • 2021-01-27 12:08

    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.

    0 讨论(0)
提交回复
热议问题