获取按天分组的行的最小值和最大值

时间:2020-08-15 13:26:45

标签: php mysql laravel eloquent

我想返回按天与Laravel Eloquent分组的每条记录的最小值和最大值,所以就这样:

表结构:费率

id     buy_rate     sell_rate     market_currency_id     created_at
==     ========     =========     ==================     ==========
1      10           7             44                     2020-10-10
2      10           9             44                     2020-10-10
3      10           8             44                     2020-10-10
4      10           12            44                     2020-10-11
5      10           14            44                     2020-10-11
6      10           13            44                     2020-10-11

现在我正在获取这样的数据:

$rates = Rate::
select('sell_rate', \DB::raw("DATE_FORMAT(created_at, %Y-%m-%d) day))
->where('market_currency_id', '=', 44)
->whereBetween('created_at', [2020-10-10, 2020-10-11])
->orderBy('created_at', 'ASC')
->get()
->toArray();

上面的代码返回:

0 => array:2 [▼
    "sell_rate" => "8"
    "day" => "2010-10-10"
]
1 => array:2 [▼
    "sell_rate" => "12"
    "day" => "2010-10-11"
]

现在,我想要得到的是这样的东西:

0 => array:2 [▼
    "sell_rate" => "8"
    "day" => "2010-10-10"
    "min_rate" => "7"
    "max_rate" => "9"

]
1 => array:2 [▼
    "sell_rate" => "13"
    "day" => "2010-10-11"
    "min_rate" => "12"
    "max_rate" => "14"
]

我尝试了很多方法,但是我没有得到想要的东西,我尝试了这样的原始选择:

$rates = Rate::
select('sell_rate', \DB::raw("DATE_FORMAT(created_at, %Y-%m-%d) day))
->selectRaw("MIN(sell_rate) AS min_rate, MAX(sell_rate) AS max_rate")
->where('market_currency_id', '=', 44)
->whereBetween('created_at', [2020-10-10, 2020-10-11])
->orderBy('created_at', 'ASC')
->get()
->toArray();

但是无法得到我想要的东西,我也不能分开做,因为有成千上万的行,谢谢!!

2 个答案:

答案 0 :(得分:4)

您还需要按天分组:

$rates = Rate::select(DB::raw("DATE_FORMAT(created_at, %Y-%m-%d) day"))
    ->selectRaw("MIN(sell_rate) AS min_rate, MAX(sell_rate) AS max_rate")
    ->where('market_currency_id', '=', 44)
    ->whereBetween('created_at', ['2020-10-10', '2020-10-11'])
    ->groupBy(DB::raw('day'))
    ->orderBy(DB::raw('day'))
    ->get()
    ->toArray();

答案 1 :(得分:1)

您可以尝试以下方法:

$rates = Rate::
select('sell_rate', \DB::raw("DATE_FORMAT(created_at, %Y-%m-%d) day"), \DB::raw("MIN(sell_rate) as min_rate"), \DB::raw("MAX(sell_rate) as max_rate"))
->where('market_currency_id', '=', 44)
->whereBetween('created_at', [2020-10-10, 2020-10-11])
->orderBy('created_at', 'ASC')
->groupBy(DB::raw('day'))
->get()
->toArray();