【问题标题】:Sum and group by month using Laravel Eloquent使用 Laravel Eloquent 按月求和和分组
【发布时间】:2021-08-10 06:09:05
【问题描述】:

我正在使用 Laravel 5.6 和 postgres 11。

我记录了不同设备类型的数量变化,如下所示:

{location_id: 1, equipment_type_id: 1, qty: 5, total: 5, date: 'YYYY-MM-DD'},
{location_id: 1, equipment_type_id: 1, qty: 5, total: 10, date: 'YYYY-MM-DD'},
{location_id: 1, equipment_type_id: 2, qty: 5, total: 5, date: 'YYYY-MM-DD'},
{location_id: 1, equipment_type_id: 1, qty: 5, total: 15, date: 'YYYY-MM-DD'} etc

我希望能够获得按月分组的每种类型的总数,但我只想获得同一个月内某个类型和位置的最新总数。例如,如果位置 1 有 3 个类型 1 的条目,我想总结该月的最后一个条目。

返回的数据如下所示:

{type: 1, data: [{month: Jan, total: 15}]},
{type: 2, data: [{month: Jan, total: 10},{month: Feb, total: 15}]}

我很快就开始了,但这种类型的查询完全超出了我的想象:

$singles = EquipmentLog::where('equipment_type_id', '=', 3)
            ->select(
                DB::raw('sum(total) as total'), 
                DB::raw("DATE_TRUNC('month',logged_at) as month")
            )
            ->groupBy('month')
            ->get();

        $totals = [
            ['name' => 'Hives - Single', 'data' => $singles],
        ];

【问题讨论】:

  • 我对这个问题有点困惑。是否要检索类型和位置的最后一个条目?
  • @SandeepDhakal 很抱歉造成混淆,我想要每种类型的总数,但只使用一个月内每个位置的最后一个条目。希望这更有意义?

标签: laravel postgresql laravel-5 eloquent


【解决方案1】:

我认为您可以通过这种方式解决此问题。尝试一下,如果出现问题,请通知我。

$sub = DB::table('equipment_logs as el')
  ->selectRaw('distinct equipment_type_id, location_id, 
  extract(year from created_at) as year,
  extract(month from created_at) as month, 
  (select total from equipment_logs 
  where location_id = el.location_id
  and equipment_type_id = el.equipment_type_id)
  and extract(year from created_at) = 
  extract(year from el.created_at)
  and extract(month from created_at) = 
  extract(month from el.created_at)
  order by created_at desc limit 1) as total')
  ->where([
    ['equipment_type_id', '=', 3],
    [ /* condition2 */],
    [ /* condition3 */]
   ]);

$data = DB::table(DB::raw("({$sub->toSql()}) as sub"))
  ->mergeBindings($sub)
  ->selectRaw('equipment_type_id,year,month,sum(total) as total')
  -> groupBy('equipment_type_id’,’year’,’month')
  ->orderByRaw('equipment_type_id,year,month')
  ->get();

【讨论】:

  • 谢谢,我得到 groupByRaw 不存在,我认为这可能不适用于 Laravel 5.6?
  • 只需将 groupByRaw 修改为 groupBy('equipment_type_id','year','month')
  • 感谢您的回复。我现在也收到此错误:SQLSTATE[42601]: Syntax error: 7 ERROR: syntax error at or near \"logged_at\"\nLINE 2: extract(year from timestamp logged_at) as year
  • 你能告诉我你的日志记录栏是什么格式吗?
  • YYYY-MM-DD - 日期类型
猜你喜欢
  • 2019-05-10
  • 2017-03-24
  • 2015-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
相关资源
最近更新 更多