Kristian
Kristian

Reputation: 21830

Rails how to calculate multiple sums from one query data

With the following two models, Company and Response, I am making a query of the total responses per company like this:

@allResponses = Company.find(current_user_company_id).responses

this gives me data like this:

[#<Response id: 1, company_id: 1, created_at: "2013-04-24 02:36:54", feedback_score: 10, feedback_explanation: "I really like the way you guys do xyz.", additional_data: "", updated_at: "2013-04-24 02:36:54">, #<Response id: 2, company_id: 1, created_at: "2013-04-25 03:51:07", feedback_score: 5, feedback_explanation: "customer service is spotty.", additional_data: "", updated_at: "2013-04-25 03:51:07">, #<Response id: 3, company_id: 1, created_at: "2013-04-25 03:52:04", feedback_score: 7, feedback_explanation: "You've got potential.", additional_data: "", updated_at: "2013-04-25 03:52:04">, #<Response id: 4, company_id: 1, created_at: "2013-04-25 03:52:18", feedback_score: 9, feedback_explanation: "Almost perfect.", additional_data: "", updated_at: "2013-04-25 03:52:18">] 

I want to get the following two variables out of this data:

@sumOfHighScores = some.thing.here       #sum of feedback_scores that are greater than 8
@sumOfLowScores = some.thing.here.too    #sum of feedback_scores that are less than 7

Upvotes: 0

Views: 311

Answers (3)

Harish Shetty
Harish Shetty

Reputation: 64363

I will perform the entire calculation in the database.

company = Company.find(current_user_company_id)
totals =  company.responses.sum(
            :feedback_score,
            :group => "CASE WHEN feedback_score < 7 THEN 'low' ELSE 'high' END")
low, high = (totals['low'] || 0), (totals['high'] || 0 )

Upvotes: 1

Aman Garg
Aman Garg

Reputation: 4218

You can try this,

@sumOfHighScores = @allResponses.select{ |response| response.feedback_score > 8 }.map(&:feedback_score).sum
@sumOfLowScores = @allResponses.select{ |response| response.feedback_score < 7 }.map(&:feedback_score).sum

Upvotes: 2

Aditya Kapoor
Aditya Kapoor

Reputation: 1570

Try this..

 @sumOfHighScores = @allResponses.select{ |response| response.feedback_score > 8 }.sum
 @sumOfLowScores = @allResponses.select{ |response| response.feedback_score < 7 }.sum

Upvotes: 1

Related Questions