Fetching Minimum/Maximum for each group in ActiveRecord

前端 未结 5 1361
说谎
说谎 2021-02-05 20:53

This is an age-old question where given a table with attributes \'type\', \'variety\' and \'price\', that you fetch the record with the minimum price for each type there is.

5条回答
  •  忘掉有多难
    2021-02-05 21:30

    You can use #find_by_sql, but this implies returning a model object, which might not be what you want.

    If you want to go bare to the metal, you can also use #select_values:

    data = ActiveRecord::Base.connection.select_values("
            SELECT f.type, f.variety, f.price
            FROM (SELECT type, MIN(price) AS minprice FROM table GROUP BY type ) AS x
            INNER JOIN table AS f ON f.type = x.type AND f.price = x.minprice")
    puts data.inspect
    [["type", "variety", 0.00]]
    

    ActiveRecord is just a tool. You use it when it's convenient. When SQL does a better job, you use that.

提交回复
热议问题