SQL >> Base de Datos >  >> RDS >> Mysql

Laravel Eloquent: agrupar y conservar la fila más reciente

Para obtener el último registro por cliente dentro de cada ciudad ordenado por created_at, usa un self join:

DB::table('yourTable as t')
->select('t.*')
->leftJoin('yourTable as t1', function ($join) {
    $join->on('t.Customer', '=', 't1.Customer')
         ->where('t.City', '=', 't1.City')
         ->whereRaw(DB::raw('t.created_at < t1.created_at'));
})
->whereNull('t1.id')
->get();

Equivale a SQL:

select t.*
from yourTable t
left join yourTable t1
  on t.Customer = t1.Customer
 and t.City = t1.City
 and t.created_at < t1.created_at
where t1.id is null;

La variante con join al máximo id por grupo también resuelve el problema greatest-n-per-group.