我可以像这样按每个月的计数对用户进行分组:
User.group('year(created_at)').group('month(created_at)').count
#=> {[2015, 4]=>90, [2015, 5]=>133, [2015, 6]=>131, [2015, 7]=>28, [2015, 8]=>45, [2015, 9]=>6}
我想创建统计数据,显示用户数是如何按月增长的。
所以它会返回这样的东西:
{[2015, 4]=>20, [2015, 5]=>40, [2015, 6]=>55, [2015, 7]=>70, [2015, 8]=>100, [2015, 9]=>130}
# each entry is a year, month and total users count from the beginning of time by the end of this month.
我怎样才能得到想要的结果?
如果可能,我正在寻找数据库级别的解决方案(ActiveRecord 查询)。
如有任何建议,我们将不胜感激。
最佳答案
所以,如果我误解了什么,请纠正我。您按月有用户注册,即 1 月有 1 个用户,2 月有 2 个用户,3 月有 3 个用户,并且您想要构建一个用户增长图表,因此您需要 1 月有 1 个用户,2 月有 3 个用户,3 月有 6 个用户。 如果是这种情况,您可以执行以下操作:
counts = {[2015, 4]=>1, [2015, 5]=>2, [2015, 6]=>3, [2015, 7]=>4, [2015, 8]=>5, [2015, 9]=>6}
keys = counts.keys # save keys => [[2015, 4], [2015, 5], [2015, 6], [2015, 7], [2015, 8], [2015, 9]]
acc_values = counts.values.dup # .dup is needed if you don't want to spoil original values
# because of for the following map! operation,
# right now acc_values returns => [1, 2, 3, 4, 5, 6]
# use map! instead of map so we have access to already changed items,
# while we iterating over the next
acc_values.map!.with_index { |val, key| key.zero? ? val : acc_values[key - 1] + val }
# => [1, 3, 6, 10, 15, 21]
# build resulting hash
acc_counts = keys.zip(acc_values).to_h
# => {[2015, 4]=>1, [2015, 5]=>3, [2015, 6]=>6, [2015, 7]=>10, [2015, 8]=>15, [2015, 9]=>21}
关于mysql - 用户分组 - 按月累计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32524837/