Laravel Group By 和其他列的总和值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30801873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:46:36  来源:igfitidea点击:

Laravel Group By and Sum total value of other column

phplaravel

提问by madnan

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.

但我无法获得每组金额的总和。

回答by haakym

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:

恐怕我现在无法用 eloquent 弄清楚,但这应该适用于查询构建器。它对我来说工作正常:

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"
  }
]