Reputation: 1347
I have users and expenditures table. Expenditures table has fields called user_id, amount, and entry_date. How can I get old those users whose sum of expenditure in the current quarter is less than sum of expenditure in the previous quarter?
users=User.all
users = users.requested_users
user.rb has_many :expenditures
expenditure.rb belongs_to :user
Upvotes: 0
Views: 48
Reputation: 1368
If your dataset is fairly small, you can use ruby to do this. If it's huge you'll need to do some group_by stuff on your database which will vary depending on which database you're using.
How about something like this (completely untested):
# user.rb
def self.requested_users
all.select{ |user| user.expenditures.last_quarter_range.sum(:amount) > user.expenditures.current_quarter_range.sum(:amount) }
end
# expenditure.rb
def self.last_quarter_range
all.where(entry_date: Date.today.last_quarter.beginning_of_quarter .. Date.today.last_quarter.end_of_quarter)
end
def self.current_quarter_range
all.where(entry_date: Date.today.beginning_of_quarter .. Date.today.end_of_quarter)
end
Upvotes: 0