Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting a Record With a Max Value When Grouping

So I have a model called 'Project' with fields 'unique_id' and 'version' (as well as other irrelevant fields like name). The unique_id is unique to each project and each project has multiple versions ie.

unique_id | version
        1       |     1
        1       |     2
        2       |     1

What I am trying to do is select the newest version of each project and add them to @projects for use by my view (where each project is displayed).

I have no idea how to do this but my thought process was to use Projects.group(:unique_id).count to get a hash of unique_id and count (aka the version) and use that information to pull each record via a loop. That seems clumsy to me. I also know there is a maximum function but that that won't pull the record, only the max value. Help?!

like image 433
Ben Avatar asked Sep 15 '25 21:09

Ben


1 Answers

Group by the unique_id and select the records with MAX version:

Project.select('MAX(version), unique_id, id, name').group(:unique_id).all
like image 194
DiegoSalazar Avatar answered Sep 17 '25 12:09

DiegoSalazar