How count by the first letters in Laravel Query Builder?

荒凉一梦 提交于 2020-02-05 05:58:25

问题


I want to make a count by the first letters... I have this column

I would like to count each OE rows and each GICS rows

I'm working with this query

$data4 = DB::table('incidencias')
   ->select(DB::raw('grupo_asig as grupo_asig'), DB::raw('count(*) as number'))
   ->whereNotIn('grupo_asig', [''])
   ->groupBy('grupo_asig')
   ->orderBy('number', 'desc')
   ->get();

回答1:


Use CASE WHEN and count the field like OE and ASIG

$data4 = DB::table('incidencias')
           ->select(DB::raw("(CASE WHEN grupo_asig LIKE 'OE%' THEN 'OE'
                                   WHEN grupo_asig LIKE 'GICS%' THEN 'GICS'
                              END) AS grupo_asig_type"), 
                    DB::raw('COUNT(*) as number'))
           ->whereNotIn('grupo_asig', [''])
           ->groupBy('grupo_asig_type')
           ->orderBy('number', 'desc')
           ->get();




回答2:


You should try to use the [LIKE][1] function then and add it to your query:

->where('grupo_asig', 'like', 'OE%')
->where('grupo_asig', 'like', 'GICS%')

Edit:

I tried a lot around and came to this solution and made a SQL fiddle: http://sqlfiddle.com/#!9/06a39b/8

Does it help you?




回答3:


You could use Collections. No real need to change your query much.

$data4 = DB::table('incidencias')
   ->select('grupo_asig')
   ->selectRaw('count(*) as number'))
   ->whereNotIn('grupo_asig', [''])
   ->groupBy('grupo_asig')
//   ->orderBy('number', 'desc') Unless you use this array somewhere, it's not needed.
   ->get(); 
use Illuminate\Support\Str;
...

// php >= 7.4.0
$oe_count = $data4->filter(fn($data) => Str::startsWith($data->grupo, 'OE '))->count();
$gigs_count = $data4->filter(fn($data) => Str::startsWith($data->grupo, 'GIGS '))->count();
// php < 7.4.0
$oe_count = $data4->filter(function ($data) {
    return Str::startsWith($data->grupo, 'OE ');
})->count();
$gigs_count = $data4->filter(function ($data) {
    return Str::startsWith($data->grupo, 'GIGS ');
})->count();

Starting with Laravel 6, you can also use cursor() instead of get() in your query to return a LazyCollection. It's faster for this scenario.




回答4:


I would suggest using a query for that:

refer to this answer


SELECT
    LEFT(grupo_asig, 1) AS first_letter,
    COUNT(*) AS total
FROM incidencias
GROUP BY first_letter



来源:https://stackoverflow.com/questions/59843084/how-count-by-the-first-letters-in-laravel-query-builder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!