Reputation: 6136
I have two models such as Doctor & Patient.
Doctor model has many patients
Patients belongs to one doctor.
Each doctor has column called fees(integer datatype)
which is to store the doctor fees. Each doctor has fixed fees like 10$, 20$ and so on.
Now I want to calculate the total fees for all patients. For example if 3 patients are exist with 3 doctors with fees 10, 20 & 30 respectively. Then total fees for all the patients will be 10+20+30 = 60. is their any way to do it sql without doing looping in rails code?
class Doctor < ActiveRecord::Base
has many :patients
end
class Patient < ActiveRecord::Base
belongs_to: doctor
end
Upvotes: 1
Views: 145
Reputation: 118261
Do as below :-
# get first all doctors
doctors = Doctor.all
total_fees = doctors.inject(0) do |sum, doctor|
# doctor.patients.count will give how many patients visited
# that specific doctor. With that count, I am multiplying that specific
# doctor's fees, which is giving each doctors earnings from all his
# patients. # inject block then summing all doctors earnings and returned back.
sum += doctor.fees * doctor.patients.size
end
total_fees
# => 60
If you like one liner -
doctors.inject(0) { |sum, doctor| sum + doctor.fees * doctor.patients.size }
After reading the post again, I came up with the below solutions(which is same as above, but no looping) :-
Doctor.joins(:patients).select("sum(doctors.fees) as total")[0].total # => 60
Here is another way and more efficient :-
Doctor.joins(:patients).sum("doctors.fees") # => 60
Upvotes: 1