Scott O'Dea
Scott O'Dea

Reputation: 132

Getting maximum values from a table column, for associated id's from another column

I need to grab the maximum spend_price for each supplier_id from a minimums table. Each supplier has multiple spend prices and I can't seem to find an effective query to pull out the maximum spend_price for each one.

I've tried ordering and grouping but it seems like a very convoluted approach

min = Minimum.where(supplier_profile_id: [10005, 100010])
min.order(spend_price: :desc, supplier_profile_id: 
   :desc).group_by(&:supplier_profile_id)
min.each do |key, value|
                        max_spend_prices << [key, value[0].spend_price]
                    end

Upvotes: 1

Views: 51

Answers (2)

lacostenycoder
lacostenycoder

Reputation: 11226

I think this is what you're looking for

Minimum
  .where(supplier_profile_id: [10005, 100010])
  .group(:supplier_profile_id)
  .maximum(:spend_price)

Upvotes: 0

Yurii
Yurii

Reputation: 691

Minimum.group(:supplier_profile_id).maximum(:spend_price)

Upvotes: 0

Related Questions