我正在尝试按年龄段列出用户数量:
Range : #Users
10-14 : 16
15-21 : 120
22-29 : 312
30-40 : 12131
41-70 : 612
71-120 : 20
我当时正在考虑创建一个静态的哈希数组:
AGE_RANGES = [
{label:"10 - 14", min:10, max:14},
{label:"15 - 21", min:15, max:21},
{label:"22 - 29", min:22, max:29},
{label:"30 - 40", min:30, max:40},
{label:"41 - 70", min:41, max:70},
{label:"71 - 120", min:71, max:120}
]
然后将其用于我的搜索过滤器以及查询。但是,我想不出一种从中获得最大性能的方法。
我在模型中的方法仅按年龄分组:
def self.group_by_ageRange(minAge, maxAge)
query = User.group("users.age")
.where("users.age BETWEEN minAge and maxAge ")
.select("users.age,
count(*) as number_of_users")
end
有什么建议么?
最佳答案
您想要构建一些如下所示的SQL:
select count(*),
case
when age between 10 and 14 then '10 - 14'
when age between 15 and 21 then '15 - 21'
-- ...
end as age_range
from users
where age between 10 and 120
group by age_range
用ActiveRecord术语来说,将是:
# First build the big ugly CASE, we can also figure out the
# overall max and min ages along the way.
min = nil
max = nil
cases = AGE_RANGES.map do |r|
min = [r[:min], min || r[:min]].min
max = [r[:max], max || r[:max]].max
"when age between #{r[:min]} and #{r[:max]} then '#{r[:min]} - #{r[:max]}'"
end
# Then away we go...
age_ranges = Users.select("count(*) as n, case #{cases.join(' ')} end as age_range")
.where(:age => min .. max)
.group('age_range')
.all
这将在
age_ranges
中留下一系列对象,这些对象将具有n
和age_range
方法。如果您要使用哈希,则:age_ranges = Hash[age_ranges.map { |r| [r.age_range, r.n] }]
当然,其中不包括没有人员的范围;我将其留给读者作为练习。
关于ruby-on-rails - 在ruby中按年龄段对用户分组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12097844/