Query last row from 2012 + all rows from 2013 + first row from 2014 using Rails(ActiveRecord) - Best Practice

StackOverflow https://stackoverflow.com/questions/23521219

Question

I finding best practice solution to fetch rows from database using this conditions:

Last row from year 2012 All rows from year 2013 and first row from 2014

Is this solvable by one query in Rails.

I have no idea how to do it by one query but only using 3 queries.

Thanks.

Was it helpful?

Solution

This is one way to do it. I'm not saying it's the best or super optimized though, depends on your data and indexes.

@measurements = Measurement.find_by_sql( 
 %{select * from measurements 
   where date_part('year', date) = 2013
   or date = (select max(date) from rounds where date_part('year', date) = 2012)
   or date = (select min(date) from rounds where date_part('year', date) = 2014)
   order by date})

Edit: I see you're using sqlite, this works for Postgres but should be easily portable.

OTHER TIPS

This has worked for me, only it was with postgres and YEAR(dt) was date_part('year',dt). Plain and simple...

Measurement.where("YEAR(dt)=2013 or dt=? or dt=?",
    Measurement.where("YEAR(dt)=2012").maximum(:dt),
    Measurement.where("YEAR(dt)=2014").minimum(:dt))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top