【问题标题】:Laravel Group By and Sum total value of other columnLaravel Group By 和 Sum 其他列的总值
【发布时间】:2015-06-13 04:13:19
【问题描述】:

我的数据库中有一个表,如下所示:

id | date       | amount
========================
1  | 2015-01-26 | 1000
2  | 2015-02-26 | 100
3  | 2014-06-26 | 10

我想按年份对记录进行分组,然后求各组金额的总和。

我可以使用以下查询找到组:

Fee::orderBy('date', 'DESC')
  ->get()
  ->groupBy(function($date) {
    return Carbon::parse($date->date)->format('Y'); // grouping by years
})

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

【问题讨论】:

  • 您应该在方法链接的末尾调用->get()/->sum('amount')。试着移动它,如果你得到你需要的东西,请告诉我们。另外,您目前是否得到一些结果或错误?如果您收到错误,请分享错误。
  • @haakym 它按年份对结果集进行分组。
  • 我意识到这一点。我在问你它是否会在你的原始代码中产生错误,或者它是否返回一组数据?
  • 我想在 laravel 中有类似的查询。 SELECT id, SUM(amount) AS "Total amount" FROM fee GROUP BY Year(date)
  • 我意识到这一点。我在问你一个问题:你问题中的代码是否有效 - 是或否?如果否,会发生什么:你得到一个错误还是你得到数据。错误或数据是什么样的?

标签: php laravel


【解决方案1】:

恐怕我现在无法用 eloquent 弄清楚,但这应该适用于查询构建器。对我来说没问题:

DB::table('fees')
    ->select(DB::raw('YEAR(date) as year'), DB::raw('sum(amount) as total'))
    ->groupBy(DB::raw('YEAR(date)') )
    ->get();

使用您在问题中输入的同一日期:

id       date                       amount
 1       2015-01-26                  1000
 2       2015-02-26                  100
 3       2014-06-26                  10

它给出了以下内容:

array:2 [▼
  0 => {#150 ▼
    +"year": 2014
    +"total": "10"
  }
  1 => {#151 ▼
    +"year": 2015
    +"total": "1100"
  }
]

【讨论】:

  • 我应用了您的解决方案,但它给出了错误。 “ strtolower() 期望参数 1 是字符串,给定对象”。但是,如果跟随它返回零(0)。 Fee::orderBy('date', 'DESC') ->get() ->groupBy(function($date) { return Carbon::parse($date->date)->format('Y'); } ) ->sum('金额');
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-12
  • 1970-01-01
  • 2017-11-10
  • 1970-01-01
  • 1970-01-01
  • 2020-12-30
  • 1970-01-01
相关资源
最近更新 更多