mysql - 用户分组 - 按月累计

标签 mysql ruby-on-rails ruby database grouping

我可以像这样按每个月的计数对用户进行分组:

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/

相关文章:

jquery - AJAX 调用由服务器处理但不会呈现?

ruby - 循环后删除空行

ruby-on-rails - 根据匹配条件替换数组元素的优雅方法是什么?

ruby - Nokogiri 通过 XML 解析失败

ruby - Rubocop:是否可以向 Metrics/AbcSize cop 添加排除项?

mysql - netcat 用于 MySQL 连接转发

MySQL - 更新所有记录以匹配最后一个

mysql - MAMP Pro MySQL 将数据库引擎更改为 InnoDB 并迁移数据库时出现问题

php - Mysql select 查询超过 8 秒但限制为 5 条记录

html - 表中的子标题 : Accessibility and Templating