【问题标题】:Get the latest row each group based on max date根据最大日期获取每组的最新行
【发布时间】:2020-08-12 13:48:16
【问题描述】:

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

我正在尝试处理这个问题

|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();

【问题讨论】:

  • 这是一个非常奇怪的日期格式
  • 这个would make a good research read 甚至可能被认为是一个副本
  • App\Price::groupBy('level_one', 'level_two')->latest('effective')->first() 返回正确的日期吗?
  • 它没有给出正确的@Tpojka
  • 这意味着 orderBy 在 groupBy 之后出现。需要子查询。

标签: php mysql laravel laravel-5 eloquent


【解决方案1】:

您的日期格式有问题。通常 eloquent 和 mysql 使用 Y-m-d 日期格式。

这样使用:

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

【讨论】:

    猜你喜欢
    • 2013-11-22
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    • 2018-02-16
    • 2023-03-07
    • 1970-01-01
    • 2021-02-04
    相关资源
    最近更新 更多