0

In my app users save a report each Friday for an organization. All my records in the reports table hold organization_id, day and workdays.

I want to get the sum of all workdays at the last Friday of each month.

With the following line I am able to select all reports for organization #8 and sum workdays for each Friday:

@all_report_sums = Report.where(:organization_id => 8).group(:day).select("day, SUM(workdays) AS sum_workdays")

The result:

[{"id":null,"day":"2017-02-03","sum_workdays":3},{"id":null,"day":"2017-02-24","sum_workdays":33},{"id":null,"day":"2017-04-07","sum_workdays":12}]

However in my output I only want the maximum dates of each month (which is the last Friday of each month) - so in my case this would be 2017-02-24 and 2017-04-07.

How can I achieve that?

Oliver
  • 1,181
  • 2
  • 12
  • 30

1 Answers1

0

This is what are you looking for

How to get the latest record from each group in ActiveRecord?

User.group(:user_id).having('day = MAX(day)')
Community
  • 1
  • 1
Hsiu Chuan Tsao
  • 1,396
  • 1
  • 12
  • 23