Reputation: 873
I'm trying to get the most recent record for a single customer on a table. Example:
ID Customer City Amount
1 Cust001 City1 2
2 Cust001 City2 3
3 Cust001 City1 1
4 Cust001 City2 1
5 Cust001 City2 3
6 Cust001 City3 1
7 Cust001 City3 1
8 Cust002 City1 2
9 Cust002 City1 1
10 Cust002 City2 3
11 Cust002 City1 2
12 Cust002 City2 1
13 Cust002 City3 2
14 Cust002 City3 3
15 Cust003 City1 1
16 Cust003 City2 3
17 Cust003 City3 2
Please note that the table also has created_at and updated_at fields. I omitted those fields for simplicity.
In the end I want my query to return for Cust001:
ID Customer City Amount
3 Cust001 City1 1
5 Cust001 City2 3
7 Cust001 City3 1
And for Cust002:
ID Customer City Amount
11 Cust002 City1 2
12 Cust002 City2 1
14 Cust002 City3 3
I've tried:
Table::where('Customer', 'Cust001')
->latest()
->groupBy('City')
->get()
and also
Table::select(DB::raw('t.*'))->from(DB::raw('(select * from table where Customer = \'Cust001\' order by created_at DESC) t'))
->groupBy('t.City')->get();
But it keeps returning the oldest record on each group (and I want the most recent).
How can I achieve this? If is easier for you guys, you can write the SQL Query here and I will find a way to "translate it" to Laravel syntax.
Upvotes: 1
Views: 3607
Reputation: 64466
To get latest record per customer among for each city based on created_at
you can use a 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();
In plain SQL it would be something like
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
Another approach with self inner join would be
select t.*
from yourTable t
join (
select Customer,City,max(ID) ID
from yourTable
group by Customer,City
) t1
on t.Customer = t1.Customer
and t.City = t1.City
and t.ID = t1.ID
Upvotes: 1