Select 在 Laravel 中按出现次数区分和排序

Select Distinct and order by occurrence in Laravel

美好的一天。我有一个 table ,如下图所示。使用 Eloquent 模型(查询构建器也可以)我希望能够 select 只有具有诉讼号码的唯一案例,同时按出现次数最多的案例排序最低出现率。

例如,在下图中,由于“CA/E/14/2011”出现了 3 次,我只想 select 一个不同的值,因此我的查询应该 return 两种情况. “CA/E/14/2011”和“CA/A/344/2015”但“CA/E/14/2011”应该排在第一位,因为它出现的次数较多。

下面的查询应该 return 所需的结果集。

SELECT COUNT(suit_number) as occurrence, suit_number
FROM records
GROUP BY suit_number
ORDER BY occurrence DESC;

Eloquent:

use App\Models\Record;

Record::selectRaw("COUNT(suit_number) as occurence, suit_number")
    ->groupBy("suit_number")
    ->orderBy("occurence", "desc")
    ->get();

SQL Fiddle

如果你只想要suit_number你可以做到

Record::selectRaw("COUNT(suit_number) as occurence, suit_number")
        ->groupBy("suit_number")
        ->orderBy("occurence", "desc")
        ->pluck('suit_number');