Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the record with the maximum price?

This returns the maxium value, not the complete record:

self.prices.maximum(:price_field)

And currently, I find the record like this:

def maximum_price
  self.prices.find(:first, :conditions => "price = #{self.prices.maximum(:price_field)}" )
end

Is this the correct way ? Because the above needs two SQL statements to make it work, and it somehow does not feel right.

Ps. Additionally, I want that if more than one record has the same "maximum" value, then it should get the one with the latest updated_at value. So that would mean another SQL statement??

Pps. Does anyone know of a good or detailed reference for AREL and non-AREL things in Rails? The Rails Guide for ActiveRecord query is just not enough!

(I'm using Rails 3)

===UPDATE===

Using AREL I do the following:

self.prices.order("updated_at DESC").maximum(:price_field)

But this only gives the maximum value, not the complete record :(
Also, is the use of maximum() really AREL?

like image 737
Zabba Avatar asked Jan 27 '11 12:01

Zabba


People also ask

How do I find the record with the max date?

Select row with max date per user using MAX() function Another way to get the latest record per user is using inner queries and Max() function. Max() function, when applied on a column, gives the maximum value of that column.

How do you get a record with maximum value for each group?

MySQL MAX() function with GROUP BY retrieves maximum value of an expression which has undergone a grouping operation (usually based upon one column or a list of comma-separated columns).

How do I find the highest record value in SQL?

To find the maximum value of a column, use the MAX() aggregate function; it takes a column name or an expression to find the maximum value. In our example, the subquery returns the highest number in the column grade (subquery: SELECT MAX(grade) FROM student ).


1 Answers

How about something like this?

self.prices.order("price DESC").first
like image 60
TK-421 Avatar answered Feb 19 '23 05:02

TK-421