根据最大日期获取每个组的最新行

时间:2020-04-28 16:43:05

标签: php mysql laravel laravel-5 eloquent

我正在尝试从最大日期的每个组中选择一个。

我正在尝试解决此问题

|NO | effective   | price     |  level_one| level_two
+---+-------------+----------+|+++++++++++|++++++++++++
|1  | 2011-12-01  |  34       |     1     |    2
|2  | 2011-16-01  |  34       |     1     |    2
|3  | 2011-18-01  | 3434      |     1     |    2
|4  | 2011-16-01  | 3554      |     1     |    3

结果应为

|NO | effective   | price     |  level_one| level_two
+---+-------------+----------+|+++++++++++|++++++++++++
|3  | 2011-18-01  | 3434      |     1     |    2
|4  | 2011-16-01  | 3554      |     1     |    3

但是结果来了

|NO | effective   | price     |  level_one| level_two
+---+-------------+----------+|+++++++++++|++++++++++++
|3  | 2011-12-01  | 34        |     1     |    2
|4  | 2011-16-01  | 3554      |     1     |    3

尝试

$price = App\Price::with('others')
    ->orderBy('effective', 'Desc')
    ->groupBy('level_one','level_two')
    ->get();

1 个答案:

答案 0 :(得分:0)

日期格式存在问题。通常,雄辩的人和mysql使用Y-m-d日期格式。

像这样使用:

$price = App\Price::with('others')
    ->orderByRaw("DATE_FORMAT(effective,'%Y-%d-%m') DESC")
    ->groupBy('level_one','level_two')
    ->get();
相关问题