Complex rails SQL query -


first of all, user has many age_demographics. agedemographic object looks this:

#<agedemographic id: 4384, user_id: 799, range: "35 - 49", percentage: 3.2, created_at: "2015-05-22 04:17:10", updated_at: "2015-05-22 04:17:10"> 

i'm building user search tool select multiple age ranges want target ("12 - 17" , "18 - 24" example). need select users have collection of age demographic objects total percentage greater 50%.

this i've started with:

 user.joins(:age_demographics).where("age_demographics.range in (?)", ["12 - 17", "18 - 24", "25 - 34"]) 

but can't figure out how tie in sum of percentages of age_demographics clause.

let me know if makes absolutely no sense.

you can use having , group methods this:

user.joins(:age_demographics)     .where("age_demographics.range in (?)", ["12 - 17", "18 - 24", "25 - 34"])     .group("users.id")     .having("sum(percentage) >= 50") 

Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -