Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select a record which has the highest value in a column in Rails

I have a column called 'frequency' in my database. I want to select the records of a particular category in which frequency is more. Like there will be 5 records of same category but each may have different frequency. Out of all these 5 records, I want the record whose value in frequency is more.

Say,

record 1 frequency value = 10
record 2 frequency value = 20
record 3 frequency value = 30
record 4 frequency value = 10
record 5 frequency value = 50
I want record 5 as my output.

Thanks.

like image 233
Ninja Boy Avatar asked Dec 24 '22 00:12

Ninja Boy


1 Answers

try doing this

Record.where(category: 'animal').maximum("value")

or you could try this

Record.where(category: 'animal').order("value DESC").first

or

# 1
Record.where(category: :animal).order(value: :desc).first

# 2
Record.where(category: :animal).order(:value).last
like image 50
C dot StrifeVII Avatar answered Jan 14 '23 05:01

C dot StrifeVII