I have a Laravel application, and I have a query that is supposed to function as follows.
company date period
apple | 2017-08-23 | live
apple | 2017-09-04 | live
apple | 2014-03-04 | history
enron | 1987-09-09 | history
tesla | 2017-07-04 | live
tesla | 2017-06-03 | live
It needs to order each company's entries by date descending, with the condition that period='live' and thus return the last "live" entry for each company. In the example above, this should return
company date
apple | 2017-09-04
tesla | 2017-07-04
I have tried to accomplish this using the query builder, as such:
return $query->where('period', '=', 'live')
->groupBy('company')
->orderBy('date','desc');
However, this first groups the results and then orders them, which gives unpredictable results. According to this question/answer, the answer lies in a subquery:
ORDER BY date and time BEFORE GROUP BY name in mysql
However, I haven't been able to incorporate this approach into my problem. Can you explain to me how to effectively resolve this issue, whether with a subquery or with a different approach, but without resorting to a raw query?