【问题标题】:Is it possible to groupBy (month) and sum (each column) in table是否可以在表中分组(月)和总和(每列)
【发布时间】:2023-04-04 08:37:01
【问题描述】:
+---------+--------+---------+---------+
| date    | type_a | type_b  | type_zzz|
+---------+--------+---------+---------+
|01-01-18 | 12     | 10      |       1 |
|02-01-18 | 2      | 5       |       1 |
|03-01-18 | 7      | 2       |       2 |
|01-02-18 | 13     | 6       |      55 |
|02-02-18 | 22     | 33      |       5 |
+---------+--------+---------+---------+

嗨,

在上面的示例中,我想知道在 Laravel 中获取结果时是否可以按月分组并对每一列求和(表是动态的,因此没有模型,有些表也没有列 'type_a'其他没有'type_zzz'等...)。

我希望从上面的表格中得到的是这样的:

"01" =>
    'type_a' : '21',
    'type_b' : '17',
    'type_zzz': '4'
 "02" => 
     'type_a' : '35',
     'type_b' : '39',
     'type_zzz': '60'

我正在使用以下代码按月对其进行分组,但我无法找到按每列返回总和的解决方案:

DB::table($id)->get()->groupBy(function($date) {
        return Carbon::parse($date->repdate)->format('m');;
  });

【问题讨论】:

  • 您的数据库中的日期实际上是d-m-y 格式,还是实际上是Y-m-d 的正确ISO 格式?是一年(2018 年)的所有值,还是您想要将不同年份的月份分组?您使用的是什么 DBMS?
  • 日期是正确的 ISO 格式 Y-m-d 并且值将来自不同的年份。我正在使用mysql。谢谢!
  • 到目前为止你得到了什么?
  • @moravac,因此,如果这些值来自不同年份,并且您按月分组,则应根据您的描述合并 2017 年 9 月和 2018 年 9 月的数据?

标签: laravel eloquent


【解决方案1】:

如果我正确理解您的问题,您可以使用 SQL 查询对值进行分组和求和:

$grouped = DB::table('table_name')
    ->selectRaw('
        SUM(type_a) AS type_a,
        SUM(type_b) AS type_b,
        SUM(type_z) AS type_z
    ')
    ->groupByRaw('MONTH(date)')
    ->get();

或者,如果您不想在每个查询中指定列名,您可以在您的集合中使用 groupByarray_columnarray_sum

$grouped = DB::table('table_name')
    ->get()
    ->groupBy(function ($item) {
        return Carbon::parse($item->date)->format('m');
    })
    ->map(function ($group) {
        $group = $group->toArray();
        $summed = [];

        $columns = array_keys($group[0]);
        array_shift($columns);

        foreach ($columns as $column) {
            $summed[$column] = array_sum(array_column($group, $column));
        }

        return $summed;
    });

【讨论】:

  • 我正在尝试第二种解决方案,但出现以下错误:array_keys() expects parameter 1 to be array, object given
  • @moravac - 我已经编辑了我的答案。不幸的是,我没有在任何地方安装 Laravel 来测试它,所以我是从内存中编写的。
  • 不走运,Call to undefined method stdClass::keys()
  • 好的,回到array_keys() 并将group 转换为数组。
  • 谢谢你!小改动:而不是:$summed[$column] = array_column($group, $column); 它必须是:$summed[$column] = array_sum(array_column($group, $column)); 再次,非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-08
  • 1970-01-01
  • 2018-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多