简体   繁体   中英

Find the last record in previous month to compare with in ruby

Bit of a strange one. Assume I have a database table in a rails 4 app like this.

data table

And this table is represented by a model, being Metric . You can see that the last metric for the previous month had a value for total_users of 100, and the most recent value for total_users is 105.

What I need to be able to do is compare the most recent value of total_users with the last one for the previous month and come up with the difference. So if we call this variable @net_addition , at the moment the value should be '5', being the difference between 100 and 105.

Obviously the latest record is easy, being Metric.order("created_at").last .

Where I am having a brain block is in finding the last record for the previous month. I'm thinking I need to group the data by month somehow, then find the most recent(but not the current) group, and within that find the last record?

the other thing I thought about was maybe looking to see if the current record is in a different month than the last record and somehow marking that record as being the one for comparison if so, so the last record in each month would end up with a flag against it?

Can anyone get me started?

You can scope by date range

start_date = 1.month.ago.beginning_of_month
end_date = 1.month.ago.end_of_month

Metric.where(created_at: start_date..end_date)
      .order(created_at: :desc).first
last_month = Time.current - 1.month
Metric.order("created_at").where(
  created_at: last_month.beginning_of_month..last_month.end_of_month
).last

Using a range creates a WHERE created_at BETWEEN a AND b clause.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM