Skip to content
Advertisement

Laravel how to get similar/most count records in a row?

I have a table like this

id     worktime_l        
1         120                 
1         120                 
1         150                 
1         210                 
1         120                

I want to get the majority or have the most count of the records. Since there are 3 120’s in the table. Query must return 120. Also, if the values are independent. I should get the lowest one. Is that possible in Laravel or in MySQL? . Thanks in advance.

Advertisement

Answer

DB::table('tablename')
->select('worktime_l')
->groupBy('worktime_l')
->orderByRaw('COUNT(*) DESC, worktime_l ASC LIMIT 1')

Here it is,

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement